wood burning stoves*
The moose likes JDBC and the fly likes usage of Class.forName() for loading driver Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "usage of Class.forName() for loading driver" Watch "usage of Class.forName() for loading driver" New topic
Author

usage of Class.forName() for loading driver

Yohan Shikari
Greenhorn

Joined: Apr 01, 2005
Posts: 13
Why do I need to use Class.forName("driver_manager class") for loading driver in JDBC?

Why can't I create an instance of the driver_manager class using the new operator?
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

You're right in a way, you could directly access the Driver for your database.

The design for JDBC is meant to hide specifics about the database type. In theory this allows you write code to access a database without tying yourself to a single vendor: you can change databases without rewriting a line of code.

If you did it the way you wanted, you would have to write a significant part of your code if you changed databases. It's not wrong, it just doesn't make use of the strengths of JDBC.

There are actually a variety of ways to make sure the driver gets loaded, but most examples only use the Class.forName() solution because it is easiest to present for the learning process. Unfortunately they usually don't mention the other options. I'm reading Core Java (seventh Ed) at the moment and they actually list a few solutions, but as an example you can specify the driver name as -Djdbc.driver=com.class.for.your.Driver on the comand line when you start your application and you don't need the Class.forName() line.

Unfortunately I'm going to make the same mistake and not list all the options either but I will mention you can often use DataSource descriptors or System.setProperty() as two more options.

Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: usage of Class.forName() for loading driver