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 Which Driver will be used? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Which Driver will be used?" Watch "Which Driver will be used?" New topic

Which Driver will be used?

an bo

Joined: Mar 24, 2009
Posts: 5
Consider a case where you have multiple drivers loaded onto your memory....

When you run getConnection(), which of the above mentioned drivers will be used to get the connection?

Thanks in Advance.

Devaka Cooray
ExamLab Creator

Joined: Jul 29, 2008
Posts: 3786

Class.forName method is used for the class loading purpose only. The driver depends on the value you passed to the getConnection method.

Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
Matt Cartwright
Ranch Hand

Joined: Aug 25, 2008
Posts: 149

documentation says:
When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.

the Class.forname() simply registers the driver with
the DriverManager.

When calling DriverManager.getConnection() the
implementation iterates over all registered drivers
and tries to connect.
If an Exception is thrown, it continues iterating.

You can have a look in the
source code.

Your Java installation comes with that includes
all source code.

Hope that helps
Peter Johnson

Joined: May 14, 2008
Posts: 5852

The key is the connection URL passed to the DriverManager.getConnection() or getDriver() methods. Compare the URLs for several different database's JDBC drivers and you will see that even though they all start with "jdbc:", after that they are quite different, with the next word usually identifying the database type. The Driver Manager, when given the connection URL, cycles through the registered JDBC drivers asking each one whether it recognizes the URL. The first driver to say this it does is the one used.

JBoss In Action
I agree. Here's the link:
subject: Which Driver will be used?
jQuery in Action, 3rd edition