Lesson 13 activity guide

Page 11

6.

Write a method body for the add method. The add method creates a new record in the database from the Employee object passed in as a parameter. Recall that the SQL command to create a new record in the database is: INSERT INTO <table> VALUES (...). a.

Delete the boiler-plate code created by NetBeans for the add method.

b.

Look at the other methods in the class. They each begin by creating an instance of a Statement object in a try-with-resources statement: try (Statement stmt = con.createStatement()) { }

c.

Inside the try block, create a query to insert the values passed in the Employee instance to the database. Your query string should look something like this: String query = "INSERT INTO EMPLOYEE VALUES (" + emp.getId() + ", '" + emp.getFirstName() + "', " + "'" + emp.getLastName() + "', " + "'" + new java.sql.Date(emp.getBirthDate().getTime()) + "'," + emp.getSalary() + ")"; Note the use of single quotes for the strings and the date.

d.

Since you are not expecting a result from the query, the appropriate Statement class method to use is updateQuery. Make sure to test to see whether the statement executed properly by looking at the integer result of the method. For example: if (stmt.executeUpdate(query) != 1) { throw new DAOException("Error adding employee"); }

e.

At the end of the try block, catch any SQLException thrown, and wrap them in the DAOException to be handled by the calling application. For example: catch (SQLException se) { throw new DAOException("Error adding employee in DAO", se); }

7.

Write a method body for the findById method. This method is used by the update and delete methods and is used to locate a single record to display. Recall that the SQL command to read a single record is: "SELECT * FROM <table> WHERE <pk>=<value>". a.

Delete the boiler-plate code created by NetBeans for the findById method.

b.

Create an instance of a Statement object in a try-with-resources block: try (Statement stmt = con.createStatement()) { }

c.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.