Creating a Method in JDeveloper to Query Data

The following steps show you how to add a simple query method to your DataHandler.java class. If DataHandler.java is not open in the JDeveloper integrated development environment (IDE), double-click the DataHandler.java file in the Application Navigator to display it in the Java Source Editor.

  1. In the DataHandler class, add the following import statements after the existing import statements to use the Statement and ResultSet JDBC classes:
    import java.sql.Statement;
    import java.sql.ResultSet;
    
  2. After the connection declaration, declare variables for Statement, ResultSet, and String objects as follows:
    Statement stmt;
    ResultSet rset;
    String query;
    String sqlString;
    
  3. Create a method called getAllEmployees, which will be used to retrieve employee information from the database. Enter the signature for the method:
    public ResultSet getAllEmployees() throws SQLException{ 
    
  4. Press the Enter key to include the closing brace for the method and a new line to start entering the method code.
  5. Call the getDBConnection method created earlier:
    getDBConnection();
    
  6. After calling the getDBConnection method, use the createStatement method of the Connection instance to provide context for executing the SQL statement and define the ResultSet type. Specify a read-only, scroll-sensitive ResultSet type as stated in the following code:
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    

    The Java Code Insight feature can help you ensure that the statement syntax is correct.

  7. Define the query and print a trace message. The following code uses a simple query to return all the rows and columns in the Employees table, where the data is ordered by the Employee ID:
    query = "SELECT * FROM Employees ORDER BY employee_id";
    System.out.println("\nExecuting query: " + query);
    
  8. Run the query and retrieve the results in the ResultSet instance as follows:
    rset = stmt.executeQuery(query); 
    
  9. Return the ResultSet object:
    return rset;
    
  10. Save your work. From the File menu, select Save All.

Example 4-3 Using the Connection, Statement, Query, and ResultSet Objects

    public ResultSet getAllEmployees() throws SQLException{
        getDBConnection(); 
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
               ResultSet.CONCUR_READ_ONLY);
        query = "SELECT * FROM Employees ORDER BY employee_id";
        System.out.println("\nExecuting query: " + query);
        rset = stmt.executeQuery(query); 
        return rset;
    }

The code for the getAllEmployees method should be as shown in Example 4-3.