Creating the Connection Method

To connect to the database, you must create a method as follows:

  1. Add the following method declaration after the connection declaration:
    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.

  2. At the end of the same line, add an open brace ({) and then press the Enter key. JDeveloper automatically creates the closing brace, and positions the cursor in a new empty line between the braces.
  3. On a new line, declare an OracleDataSource instance as follows:
    OracleDataSource ds;
    
  4. Enter the following to create a new OracleDataSource object:
    ds = new OracleDataSource();
    
  5. Start to enter the following to set the URL for the 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.

    Figure 3-7 Java Code Insight

    Description of Figure 3-7 follows
    Description of "Figure 3-7 Java Code Insight"
  6. On the next line, enter the following:
    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);
            
        }
    }
    
  7. Compile your class to ensure that there are no syntax errors. To do this, right-click in the Java Source Editor, and select Make from the shortcut menu. A Successful compilation message is displayed in the Log window below the Java Source Editor window.