File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases 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
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "usage of Class.forName() for loading driver" Watch "usage of Class.forName() for loading driver" New topic

usage of Class.forName() for loading driver

Yohan Shikari

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

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.

I agree. Here's the link:
subject: usage of Class.forName() for loading driver
It's not a secret anymore!