Friday, June 01, 2007

Why We Have DriverManager.registerDriver()

When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager”-the Driver interface of JDBC API has made it very clear about its intentions. So the user now can register the Driver by calling Class.forName(the driver name).This is a simplest case of dynamic class loading and is used extensively in implementing Enterprise systems. For others, there are two choices: either call Class.forName() or call DriverManager.registerDriver().

Let us do the latter.

Driver driver=new com.mysql.jdbc.Driver();

DriverManager.registerDriver(driver);

The point which I am curious about is that now the DriverManager has two Driver instances registered with it and every time we try to get a connection, it iterates over the list containing these two drivers.Well! Our intention was to have a single driver instance and we end up having two. Why we have two driver instances is simple as in Driver class we have a static block as

static

{

try

{

DriverManager.registerDriver(new Driver());

}

catch(SQLException E)

{

throw new RuntimeException("Can't register driver!");

}

}

So when we call new Driver(), first registration happens and the next is performed by us.

Well! After this long story, the only thing which I am curious about is “Why we have a register method in DriverManager class where we can do our job with Class.forName() or just calling new Driver()”.

Since I have never used DriverManager.registerDriver() nor I have seen somebody using it.I would appreciate if someone comes up with its usage.