Creating a Method for Deleting Data

The method created in the following steps is used to delete employee records by ID:

  1. Open DataHandler.java in the Java Source Editor.
  2. Declare a new method that identifies the employee record to be deleted:
    public String deleteEmployeeById(int id) throws SQLException {
     
    }
    
  3. Connect to the database as before.
    getDBConnection();
    
  4. Create a Statement object, define a ResultSet type as before, and formulate the SQL statement. Add a trace message to assist with debugging.
    stmt =
      conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                           ResultSet.CONCUR_READ_ONLY);
    sqlString = "DELETE FROM Employees WHERE employee_id = " + id;
    System.out.println("\nExecuting: " + sqlString);
    
  5. Run the SQL statement.
    stmt.execute(sqlString);
    
  6. If the SQL statement runs without any errors, return the word, Success.
    return "success";
    

    The following code example shows the code for the deleteEmployeeById() method.

    Method for Deleting an Employee Record

    public String deleteEmployeeById(int id) throws SQLException {
    getDBConnection();
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                                    ResultSet.CONCUR_READ_ONLY);
        sqlString = "DELETE FROM Employees WHERE employee_id = " + id;
        System.out.println("\nExecuting: " + sqlString);
        stmt.execute(sqlString);
        return "success";
    }