wood burning stoves 2.0*
The moose likes JDBC 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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Which Driver will be used?" Watch "Which Driver will be used?" New topic
Author

Which Driver will be used?

an bo
Greenhorn

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
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3060
    
  38

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 DriverManager.java
source code.

Your Java installation comes with src.zip that includes
all source code.

Hope that helps
Matt
Peter Johnson
author
Bartender

Joined: May 14, 2008
Posts: 5823
    
    7

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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Which Driver will be used?