Monday, January 19, 2009

2.1.1 Opening a Connection;

The traditional way to establish a connection with a database is to call the method DriverManager.getConnection. This method takes a string containing a URL. The DriverManager class, referred to as the JDBC management layer, attempts to locate a driver that can connect to the database represented by that URL. The DriverManager class maintains a list of registered Driver classes, and when the method getConnection is called, it checks with each driver in the list until it finds one that can connect to the database specified in the URL. The Driver method connect uses this URL to actually establish the connection.
A user can bypass the JDBC management layer and call Driver methods directly. This could be useful in the rare case that two drivers can connect to a database and the user wants to explicitly select a particular driver. Normally, however, it is much easier to just let the DriverManager class handle opening a connection.
The following code exemplifies opening a connection to a database located at the URL

jdbc:odbc:wombat with the user ID oboy and the password 12Java:
String url = "jdbc:odbc:wombat";
Connection con = DriverManager.getConnection(url, "oboy", "12Java");

The DataSource interface, an alternative to the DriverManager, is the preferred means of establishing a connection. When a DataSource class has been implemented appropriately, a DataSource object can be used to produce Connection objects that participate in connection pooling and/or Connection objects that can participate in distributed transactions. See the chapter "DataSource" for more information and to see example code for creating a connection using a DataSource object. That chapter also explains why using a DataSource object is a better way to create a connection.
An application uses a Connection object produced by a DataSource object in essentially the same way it uses a Connection object produced by the DriverManager facility. As is always the case, an application should include a finally block to assure that connections are closed even if an exception is thrown. This is even more important if the Connection object is a pooled connection because it makes sure that a valid connection will always be put back into the pool of available connections. The following code fragment, in which con is Connection object, is an example of a finally block that closes a connection if it is valid.

finally{
if (con != null) con.close();
}

Note that a finally block appears after a try/catch block, as shown in the following example, where ds is a DataSource object.

try {
Connection con = ds.getConnection("user", "secret");
// . . . code to do the application's work
} catch {
// . . . code to handle an SQLException
} finally {
if (con != null) con.close();
}

0 Comments: