Now that we have connected to the database, it is time to begin communicating with it.
JDBC provides a very straightforward class to take care of executing static SQL queries, the
Statement interface. A
Statement is generated from a call to the
Connection connection = DriverManager.getConnection(url); Statement statement = connection.createStatement();
Statement object is created it can be used to execute SQL queries and return a
ResultSet object, which is essentially a Java representation of a table from the database. The
ResultSet can then be used in the logic of your program.
Statement objects, just like
Connection objects, also need to be closed when you are finished using them and are best included inside the same
try-with-resources block that a
Connection is opened in.
There is also an extension of
PreparedStatement that is used to execute a precompiled SQL statement multiple times and with greater efficiency. As your program interacts more and more with the database you may find that a
PreparedStatement might improve your performance.
For now, let’s set up our
Statement objects that we will use in each of our remaining
Inside CustomerDaoService.java you will see that we have added the
try-with-resources stubs to each of the remaining methods. We’ve added some whitespace to increase readability as well. Declare a new
statement, and set it equal to the return of calling the
.createStatement() method on the
connection object, do this for each of the following:
Add an import statement to
CustomerDaoService for the
Statement interface, it comes from the
java.sql as well.