Creating a Method to Identify an Employee Record

The method you create in these steps is used to find the record for a particular employee. It is used when a user wants to edit or delete a particular employee record, and selects a link for that employee on the Employee.java page.

  1. If the DataHandler class is not already open in the Java Source Editor, double-click it in the Application Navigator to open it.
  2. In the DataHandler class, declare a new method that identifies the employee record to be updated:
    public Employee findEmployeeById(int id) throws SQLException {
     
    }
    
  3. Within the body of this method, create a new instance of the Employee bean called selectedEmp.
    Employee selectedEmp = new Employee();
    
  4. Connect to the database.
    getDBConnection();
    
  5. Create a Statement object, define a ResultSet type, and formulate the query. Add a trace message to assist with debugging.
    stmt =
      conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                           ResultSet.CONCUR_READ_ONLY);
    query = "SELECT * FROM Employees WHERE employee_id = " + id;
    System.out.println("\nExecuting: " + query);
    
  6. Run the query and use a ResultSet object to contain the result.
    rset = stmt.executeQuery(query);
    
  7. Use the result set returned in rset to populate the fields of the employee bean using the set methods of the bean.
    while (rset.next()) {
      selectedEmp.setEmployeeId(new Integer(rset.getInt("employee_id")));
      selectedEmp.setFirstName(rset.getString("first_name"));
      selectedEmp.setLastName(rset.getString("last_name"));
      selectedEmp.setEmail(rset.getString("email"));
      selectedEmp.setPhoneNumber(rset.getString("phone_number"));
      selectedEmp.setHireDate(rset.getDate("hire_date"));
      selectedEmp.setSalary(new Double(rset.getDouble("salary")));
      selectedEmp.setJobId(rset.getString("job_id"));
    }
    
  8. Return the populated object.
    return selectedEmp;