Java Reference
In-Depth Information
118. Connection connection = null;
119. try {
120. connection = getConnection();
121. PreparedStatement statement = connection.prepareStatement(sql);
122. ResultSet resultSet = statement.executeQuery();
123. while (resultSet.next()) {
124. Category category = new Category();
125. category.setId(resultSet.getLong("id"));
126. category.setCategoryDescription(resultSet
127. .getString("category_description"));
128. result.add(category);
129. }
130. } catch (SQLException ex) {
131. ex.printStackTrace();
132. } finally {
133. closeConnection(connection);
134. }
135. return result;
136. }
137.
138. public void insert(Book book) {
139. }
140.
141. public void update(Book book) {
142. }
143.
144. public void delete(Long bookId) {
145.
146. }
147. }
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.
 
Search WWH ::




Custom Search