Recent site activity

Class.forName() and DriverManager.getConnection()

Question : How does the following code works?

Class.forName("some.database.Driver");
Connection conn = DriverManager.getConnection("connection_url", "username", "password");

Answer:
A half-baked answer would be that Class.forName() loads the database driver class some.database.Driver, and DriverManager.getConnection() returns the appropriate Connection instance based on the 'connection_url' provided.

Let's figure out what actually happens.

The Class.forName() method is responsible of loading the class some.database.Driver. We know that right after loading a class, it's static initializers are executed. The static intializer within some.database.Driver would look something like:

static {
  try{
    java.sql.DriverManager.registerDriver( new Driver() );
  } catch(SQLException e) { throw new RuntimeException("Can't register driver!") }
}

The Driver class tries to register it's own instance with the DriverManager.

Now when we call DriverManager.getConnection(), it iterates through all the drivers registered with it and checks the appropriate driver for the 'connection_url'. If you examine the code in the class you would find a method getDriver() that does this.


public static Driver getDriver(String url) throws SQLException {
  Enumeration e = drivers.elements();
  while(e.hasMoreElements()) {
    Driver d = (Driver)e.nextElement();
    if ( d.acceptsURL(url) ) return d;
  }
  throw new SQLException("No driver found for " + url);
}

As you can observe, the acceptsURL() method is called for each registered drivers and the first driver that belives it could connect to the specified database is returned.