32 CHAPTER 1: Introducing Java Web Development
- Connection connection = null;
- try {
- connection = getConnection();
- PreparedStatement statement = connection.prepareStatement(sql);
- ResultSet resultSet = statement.executeQuery();
- while (resultSet.next()) {
- Category category = new Category();
- category.setId(resultSet.getLong("id"));
- category.setCategoryDescription(resultSet
- .getString("category_description"));
- result.add(category);
- }
- } catch (SQLException ex) {
- ex.printStackTrace();
- } finally {
- closeConnection(connection);
- }
- return result;
- }
- public void insert(Book book) {
- }
- public void update(Book book) {
- }
- public void delete(Long bookId) {
- }
- }
Listing 1-8 is an implementation of the BookDao interface for interacting with; this interaction includes
connecting to the database and selecting, deleting, and updating data via pure JDBC. JDBC
provides the driver that is specific to each database and that allows Java code the database.
Lines 18 to 37: These lines show the code required for managing a JDBC
connection.
Line 26: The getConnection() method returns a driver-implemented java.sql.
Connection interface. This interface allows you to run SQL statements against
the database. For this to work, you need to provide a MySQL Connector/J JAR
file. A MySQL Connector/J is a native Java driver that converts JDBC calls into
a network protocol the MySQL database can understand. The DriverManager
manages drivers and provides static methods for establishing connections to
the database.
Note You can download the MySQL Connector/J from http://dev.mysql.com/downloads/
connector/j/. Place this connector JAR in the classpath of the project.