To connect to the database, you must create a method as follows:
public void getDBConnection() throws SQLException
The Java Code Insight feature displays a message reminding you to import the SQLException
error handling package. Press the Alt+Enter keys to import it. The import java.sql.SQLException
statement is added to the list of import packages.
{
) and then press the Enter key. JDeveloper automatically creates the closing brace, and positions the cursor in a new empty line between the braces.OracleDataSource
instance as follows:
OracleDataSource ds;
OracleDataSource
object:
ds = new OracleDataSource();
DataSource
object:
ds.setURL(jdbcUrl);
Java Code Insight prompts you by providing you with a list of available OracleDataSource
methods. Scroll through the list to select the setURL(String)
method, and press the Enter key to select it into your code. In the parentheses for this function, enter jdbcUrl
in place of arg0
.
Figure 3-7 shows how the Java Code Insight feature in JDeveloper helps you with inserting code.
conn = ds.getConnection(userid,password);
As usual, Java Code Insight will prompt you with a list of methods for ds
. This time, select getConnection(String,String)
. In the parentheses, enter userid
,password
. End the line with a semicolon (;
).
Your code should look similar to the code in the following code example.
Adding a Method to Connect to the Database
package hr; import java.sql.Connection; import java.sql.SQLException; import oracle.jdbc.pool.OracleDataSource; public class DataHandler { public DataHandler() { } String jdbcUrl = null; String userid = null; String password = null; Connection conn; public void getDBConnection() throws SQLException{ OracleDataSource ds; ds = new OracleDataSource(); ds.setURL(jdbcUrl); conn=ds.getConnection(userid,password); } }
Successful compilation
message is displayed in the Log window below the Java Source Editor window.