tags:

views:

419

answers:

5

There are two ways to load a driver:

  1. Class.forName()

  2. DriverManager.registerDriver()

Method 1 internally also calls DriverManager.registerDriver and method 1 is the preferred way.

But why? Is there any small difference or is performance etc. better?
Any views are appreciated..

+1  A: 

Reading the JavaDoc it looks like Class.forName was required to start with, and then things changed so that it was no longer the prefered way (or the required way).

TofuBeer
Um... I don't think that link is correct.
Michael Borgwardt
fixed, thanks (I was reading up on what it was saying and I guess I forgot to re-grab the link :-)
TofuBeer
+1  A: 

I have to say, your life will be much easier if you construct a driver instance by statically reference the driver. Once you have that, you can ignore DriverManager which made of evil.

Tom Hawtin - tackline
+1  A: 

The JDBC API Tutorial and Reference is the best reference for such questions, a section of which addresses the role played by the Driver and DriverManager classes.

All Driver classes are expected to have a static initializer that is responsible for creating an instance of that Driver, and register it with the DriverManager, when the Driver class is loaded.

Additionally, the DriverManager.getConnection() is probably the only user-space friendly method in the class. Most of the other methods are usually not used by most developers using the JDBC API. So the old adage still stands - use Class.forName() to load the driver, and then use DriverManager.getConnection() to get a connection to the database.

Vineet Reynolds
+1  A: 

"is performance etc. better?"

I would say that performance for this one-time operation is the least of your worries.

If you're using a Java EE app server the answer is "neither". You should be setting up a connection pool and let it handle loading the driver and handing out the connections.

duffymo
i agree with your point.
harshit
+2  A: 

Hi harshit. If you use Class.forName(), then you are not required to have any compile-time dependencies on a particular JDBC driver. This is particularly useful when you are writing code that can work with a variety of databases.

Consider the following code:

// Register the PostgreSQL driver
Class.forName("org.postgresql.Driver");

Now compare it to:

import org.postgresql.Driver;

// Register the PostgreSQL driver
DriverManager.registerDriver(new Driver());

And consider that in the first example, the class name could also have come from a properties file, XML file, etc., depending on what's convenient for your application.

Matt Solnit