Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

usage of Class.forName() for loading driver

 
Yohan Shikari
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic