Monday, January 19, 2009

3.1.2 Establishing a Connection

Once the Driver classes have been loaded and registered with the DriverManager class, they are available for establishing a connection with a database. When a request for a connection is made with a call to the DriverManager.getConnection method, the DriverManager tests each driver in turn to see if it can establish a connection.
It may sometimes be the case that more than one JDBC driver is capable of connecting to a given URL. For example, when connecting to a given remote database, it might be possible to use a JDBC-ODBC bridge driver, a JDBC-to-generic-network-protocol driver, or a driver supplied by the database vendor. In such cases, the order in which the drivers are tested is significant because the DriverManager will use the first driver it finds that can successfully connect to the given URL.
First the DriverManager tries to use each driver in the order it was registered. (The drivers listed in jdbc.drivers are always registered first.) It will skip any drivers that are untrusted code unless they have been loaded from the same source as the code that is trying to open the connection.
It tests the drivers by calling the method Driver.connect on each one in turn, passing them the URL that the user originally passed to the method DriverManager.getConnection. The first driver that recognizes the URL makes the connection.
At first glance this may seem inefficient, but it requires only a few procedure calls and string comparisons per connection since it is unlikely that dozens of drivers will be loaded concurrently.
The following code is an example of all that is normally needed to set up a connection with a driver such as a JDBC-ODBC bridge driver.

Class.forName("jdbc.odbc.JdbcOdbcDriver"); //loads the driver
String url = "jdbc:odbc:fred";
Connection con = DriverManager.getConnection(
url, "userID", "passwd");

The variable con represents a connection to the data source "fred" that can be used to create and execute SQL statements.
With the addition of the javax.sql package, a DataSource object can be used to establish a connection with a data source. The DriverManager can still be used, but a DataSource object offers several advantages over the DriverManager and is the preferred alternative. Developers who are writing Enterprise JavaBeans components, however, should always use a DataSource object instead of the DriverManager. Using a properly implemented DataSource object produces connections that are pooled and that can participate in distributed transactions. See the chapter "DataSource" for more information.

0 Comments: