Forums Register Login

usage of Class.forName() for loading driver

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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
"Don't believe every tiny ad you see on the internet. But this one is rock solid." - George Washington
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1016 times.
Similar Threads
DriverManager class
Doubt on JDBC class.forname..
Confusion in Class.forName() :confused:
class.forName
Need for Class Loading using Class.forName
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:28:58.