In this article we delve into the details of a DriverManager and how it manages to locate the appropriate Driver class to establish database connection.
Database connection
The database driver is responsible to establish connection to the database. An application should not instantiate a driver class directly and instead should let the DriverManager return a Connection.
Connection con = DriverManager.getConnection(url)
![]() |
DriverManager |
Registering a driver
DriverManager.registerDriver(driverInstance);
Service provider mechanism
When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager else it won’t be available in the drivers cache of DriverManager.
public class DriverOne implements Driver { private static Driver INSTANCE = new DriverOne(); static { try { DriverManager.registerDriver(INSTANCE); } catch (SQLException e) { //log error } } ... }
Selecting a driver
acceptsURL(url)
, to make sure the right driver is selected for the JDBC URL.DriverOne
public class DriverOne implements Driver { private static Driver INSTANCE = new DriverOne(); static { try { DriverManager.registerDriver(INSTANCE); } catch (SQLException e) { //log error } } @Override public Connection connect(String url, Properties info) throws SQLException { if (!acceptsURL(url)) { return null; } return DEFAULT_CONNECTION; } @Override public boolean acceptsURL(String url) throws SQLException { return url.startsWith("jdbc:driverOne:"); } ... }
DriverTwo
public class DriverTwo implements Driver { .. static { try { DriverManager.registerDriver(INSTANCE); } catch (SQLException e) { //log error } } .. }
Suppose we register DriverOne and DriverTwo, both will be available in the cache of DriverManager. We won’t register DriverThree so it won’t be available in the cache.
public void testRegisteredDrivers() { Enumeration drivers = DriverManager.getDrivers(); while(drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); assertTrue(driver instanceof JdbcOdbcDriver || driver instanceof DriverOne || driver instanceof DriverTwo); } }
public void testDriverOne() throws SQLException { Driver driverOne = DriverManager.getDriver("jdbc:driverOne:"); assertTrue(driverOne instanceof DriverOne); }
SQLException
public void testNoSuitableDriverSqlException() { try { DriverManager.getDriver("invalid"); fail("No driver for this URL, should have thrown exception!"); } catch (SQLException e) { //expected } }