wood burning stoves
The moose likes JDBC and Relational Databases and the fly likes Without using Class.forName... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Without using Class.forName..." Watch "Without using Class.forName..." New topic

Without using Class.forName...

Jyothi Lature
Ranch Hand

Joined: Oct 31, 2001
Posts: 60
Is there a way to connect to the database without using Class.forName (" ") in java?

Jyothi<br />Sun Certified Java Programmer<br />Brainbench Certified for Javascript
vinod sharma

Joined: Sep 04, 2004
Posts: 2
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());
Julian Kennedy
Ranch Hand

Joined: Aug 02, 2004
Posts: 823
Drivers can also be registered by including the class names in the jdbc.drivers system property. However, the current preferred method of connection to a JDBC database is using a DataSource object. Here is an example:

Is there a particular reason for your question?

Hope you find this useful.

David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Originally posted by vinod sharma:
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());

This is not recommended, it can result in the Driver being registered twice. Once by the Driver class when the class loads in the ClassLoader, and the second time since you register it explicitly. 99.9% of the time it wont be an issue, but it means DriverManager.deregisterDriver(Driver driver) won't work, it will only remove one instance.

If you are prepared to hard-code the driver class, using Class c = oracle.jdbc.driver.OracleDriver.class will work the same as Class.forName(...), but is a pointless substitution, you might as well use Class.forName(...).

In the API docs for the DriverManager class, it shows the other preferred way, which is to include the Driver class on the command line with the -Djdbc.drivers=(colon separated fully qualified class list). This will automatically load the listed Drivers for you, without needing Class.forName(...) or any equivalent. The -D option could also be added to the Java system properties file, but this probably isn't a good idea. You may need to change a Driver and forget to update the file, and it would be nearly impossible to debug.

Julian is correct in saying the using a DataSource is the real preferred way, and I've heard mention that the DriverManager mechanism may be removed or deprecated in future in preference to using DataSources.
Jyothi Lature
Ranch Hand

Joined: Oct 31, 2001
Posts: 60
Thank you all...!

It was asked in one of the interviews....
I agree. Here's the link: http://aspose.com/file-tools
subject: Without using Class.forName...
jQuery in Action, 3rd edition