wood burning stoves
The moose likes JDBC and Relational Databases and the fly likes JDBC Drivers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "JDBC Drivers" Watch "JDBC Drivers" New topic

JDBC Drivers

David O'Meara

Joined: Mar 06, 2001
Posts: 13459

The first step to using a database in java is a call to:
Class.forName("driver name");
Class.forName("driver name").newInstance();
Now, my understanding is that this is so that a static block in the driver can register the driver so that a call to DriverManager.getConnection knows which driver to call without the user having to hard code it.
My question is: is there a difference between the two calls? I tend to favour the first one since there's no point instantiating an object if you aren't going to use it, but am I missing something? Many of the sample JDBC code I see flying around uses the second version.
On a related note, it would appear that the above code would only allow a single database at a time. If you want multiple databases is it acceptable to use...
Driver oracleDriver = (Driver)Class.forName("oracle driver").newInstance();
Driver oracleDriver = (Driver)Class.forName("jdbc-odbc").newInstance();
and then obtain Connections individually?
Just thinking out loud.
rani bedi
Ranch Hand

Joined: Feb 06, 2001
Posts: 358
According to JAVA API http://java.sun.com/j2se/1.3/docs/api/index.html
Instances of the class Class represent classes and interfaces in a running Java application. Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The static method forName(String className) returns the Class object associated with the class or interface with the given string name.
The method newInstance() creates a new instance of the class represented by this Class object.
So we see that there is no use to using the newInstance() method since we just have to load the JDBC driver which is already being accomplished by calling the forName() static method of the Class class.

Cheers,<br />Rani<br />SCJP, SCWCD, SCBCD
I agree. Here's the link: http://aspose.com/file-tools
subject: JDBC Drivers
It's not a secret anymore!