A driver is loaded using: Class.forName(); And we obtain the connection using: DriverManager.getConnection(); Now the question is how does the DriverManager class now which driver to use to get the connection. This is what a few people asked me.
Hello Abby, please change your display name as Ernest asks you!
When you load the driver class with Class.forName("..."), the JDBC driver registers itself with the DriverManager. By doing this, it tells the DriverManager which kind of JDBC URL this driver is for.
When you ask the DriverManager for a connection by calling getConnection(...), the DriverManager uses the JDBC URL that you supply to look in its registry of drivers, and picks a driver that can handle that URL.
When you call Class.forName the class that you pass to it registers itself with the DriverManager. Then when DriverManager.getConnection is called the DriverManager iterates through all registered drivers and queries them if they recognize the passed in URL. If the driver accepts the URL its getConnection method is called.
Here is an implementation of a JDBC driver class I created for my JAMon Driver. JAMon responds to any jdbc url that starts with 'jdbc:jamon:'. JAMon is simply a proxy driver that wraps other drivers to track performance, but other drivers would work the same way.
Thanks Steve, That clears my doubt drivers. But then again if I load multiple drivers one after another using multiple Class.forname() statements, which driver will get used? Or will the DriverManager pick the first suitable one? Also if any other section of the program has loaded a driver previously(which is not a good practice) could that driver get used. So is there any way I could force it to use a specific driver?