Exploring the JDBC Infrastructure
JDBC provides a standard way for Java applications to access data stored in a database. The core of the
JDBC infrastructure is a driver that is specific to each database; it is this driver that allows Java code to
access the database.
Once a driver is loaded, it registers itself with a java.sql.DriverManager class. This class manages a
list of drivers and provides static methods for establishing connections to the database. The
DriverManager's getConnection() method returns a driver-implemented java.sql.Connection interface.
This interface allows you to run SQL statements against the database.
The JDBC framework is quite complex and well-tested; however, with this complexity comes difficulty
in development. The first level of complexity lies in making sure your code manages the connections to
the database. A connection is a scarce resource and is very expensive to establish. Generally, the database
creates a thread or spawns a child process for each connection. Also, the number of concurrent
connections is usually limited, and an excessive number of open connections slows down the database.
We will show you how Spring helps manage this complexity, but before we can proceed any further,
we need to show you how to select, delete, and update data in pure JDBC.
Let's create a plain form of implementation of the ContactDao interface for interacting with the
database via pure JDBC. Keeping in mind what we already know about database connections, we take
the cautious and expensive (in terms of performance) approach of creating a connection for each
statement. This greatly degrades the performance of Java and adds extra stress to the database because a
connection has to be established for each query. However, if we kept a connection open, we could bring
the database server to a halt. Listing 8-7 shows the code required for managing a JDBC connection, using
MySQL as an example.
Listing 8-7. Managing a JDBC Connection
public class PlainContactDao implements ContactDao {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
// noop
}
}
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/prospring3_ch8",
"prospring3", "prospring3");
}
private void closeConnection(Connection connection) {
if (connection == null) return;
try {
connection.close();
} catch (SQLException ex) {
// noop
}
}
...
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home