Creating a Java Method for Filtering Results

The following steps describe how you can create the getEmployeesByName method. This method enables users to filter employees by their first or last name.

  1. From the Application Navigator, open the DataHandler.java class in the Java Visual Editor.
  2. After the getAllEmployees method, declare the getEmployeesByName method as follows:
    public ResultSet getEmployeesByName(String name) throws SQLException {
    
    }
    
  3. Within the body of the method, add the following code to convert the name to uppercase to enable more search hits:
    name = name.toUpperCase();
    
  4. Call the method to connect to the database:
    getDBConnection();
    
  5. Specify the ResultSet type and create the query:
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
                                ResultSet.CONCUR_READ_ONLY);
    query =
    "SELECT * FROM Employees WHERE UPPER(first_name) LIKE \'%" + name + "%\'" +
    " OR UPPER(last_name) LIKE \'%" + name + "%\' ORDER BY employee_id";
    
  6. Print a trace message:
    System.out.println("\nExecuting query: " + query);
    
  7. Run the query and return a result set as before:
    rset = stmt.executeQuery(query);
    return rset; 
    
  8. Save the file and compile it to ensure there are no compilation errors.