Selecting and deregistering JDBC drivers

During the course of your application you may need to select or remove specific drivers from the DriverManager list. These methods are useful if, for example, you implement a Factory design pattern to support multiple databases.

Within your Factory class you could use DriverManager to pre-register the JDBC drivers you need for connecting to the supported databases. When a request for a Connection object occurs, your factory selects the proper driver from DriverManager and then creates the Connection object. In this manner you can support multiple databases and provide the correct Connection object to the client based on its request.

XRef Part III, "Using Java Data Access Design Patterns," covers the Factory pattern and other standard design patterns that you may apply to JDBC.

The two methods for selecting drivers are DriverManager.getDriver() and DriverManager.getDrivers(). The first returns a specific Driver object when you pass it the JDBC URL identifying your database. (I cover JDBC URLs in the next section.) The second returns an Enumeration object so that you can iterate through a list of Driver objects until you find the one you want. The following snippet provides an example of how to use the DriverManager.getDrivers() method:

  • Assume valid JDBC drivers have been registered
  • Enumeration object needed to obtain registered drivers Enumeration driverEnum = DriverManager.getDrivers();
  • List the drivers.

while(driverEnum.hasMoreElements()) { //Cast to a Driver object

Driver driver = (Driver)driverEnum.nextElement();

String str = "Driver name is: " + driver.getClass().getName(); System.out.println(str);

Although I just list the driver's name in the snippet, you can use the Driver object retrieved from the Enumeration object to connect to a database or use the driver with DriverManager.deregisterDriver() to explicitly remove it from the DriverManager object's internal list.

XRef I cover JDBC URLs in the next section, "Opening connections." In brief, a JDBC URL provides instructions to the JDBC driver on how to connect to your database.

If for any reason you need to remove support for a database you can call the

DriverManager.deregisterDriver() method to remove a registered Driver from DriverManager. The method is similar to the registerDriver() method in that it takes a Driver object as a parameter.

0 0

Post a comment

  • Receive news updates via email from this site