Creating a Method to Insert Data

In the following steps, you will create a method for inserting a new employee record.

  1. Open DataHandler.java in the Java Source Editor.
  2. Declare a method to add a new employee record.
    public String addEmployee(String first_name, 
      String last_name, String email, 
      String phone_number, String job_id, int salary) throws SQLException {
     
    }
    
  3. Add a line to connect to the database.
    getDBConnection();
    
  4. Create a Statement object, define a ResultSet type as before, and formulate the SQL statement.
    stmt =
      conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
                           ResultSet.CONCUR_READ_ONLY);
    sqlString =
      "INSERT INTO Employees VALUES (EMPLOYEES_SEQ.nextval, '" + 
      first_name + "','" + 
      last_name + "','" + 
      email + "','" + 
      phone_number + "'," +
      "SYSDATE, '" + 
      job_id + "', " + 
      salary + ",.30,100,80)";
    

    Note:

    The last three columns (Commission, ManagerId, and DepartmentId) contain hard-coded values for the sample application.

  5. Add a trace message, and then run the SQL statement.
  6. Return a message that says "success" if the insertion was successful.
  7. Make the file to check for syntax errors.

Example 5-2 Method for Adding a New Employee Record

public String addEmployee(String first_name, 
  String last_name, String email, 
  String phone_number, String job_id, int salary) throws SQLException {
  getDBConnection();
  stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
                              ResultSet.CONCUR_READ_ONLY);
  sqlString =
    "INSERT INTO Employees VALUES (EMPLOYEES_SEQ.nextval, '" + 
     first_name + "','" + 
    last_name + "','" + 
    email + "','" + 
    phone_number + "'," +
    "SYSDATE, '" + 
    job_id + "', " + 
    salary + ",.30,100,80)";
    
  System.out.println("\nInserting: " + sqlString);
  stmt.execute(sqlString);
  return "success";
}

Example 5-2 shows the code for the addEmployee() method.