I understand that from my program I can register a JDBC driver by using the Class.forname(driver) method.
I tested this method with two DBMSs (Derby and Access). What I did is as follows:
First I used Class.forname(driver) method and the program ran successfully and fetched data from the database.
Next time I commented the forname(driver) method (as well as the corresponding ClassNotFoundException) and then also the program ran successfully!!!
So, my question is how the program could fetch the data when at the second time I did not register the JDBC driver?? Please tell me. I am new to it.
(I hadn't until now, and didn't know this capability existed, so thanks! I don't do much that requires this, but it's still interesting.)
Joined: Dec 18, 2002
I have read it. It says,
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
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.
I just can't understand why applications no longer need to explicitly load JDBC drivers? How java finds it out? What does it mean by drivers loaded at initialization?
Please help me.
Joined: Dec 18, 2002
I think I got it. But partly it is still unclear.
I got the fact that ServiceLoader mechanism needs the driver jar file to keep a file named java.sql.Driver in the META-INF\services folder and the content of the file should be name of the driver class that java automatically loads at the run time.
I was trying the Derby database. So looked at its java.sql.Driver file (in the derby.jar) and its content is:
What I did not get is that if org.apache.derby.jdbc.AutoloadedDriver is being loaded if I don't manually load any driver, how the driver org.apache.derby.jdbc.EmbeddedDriver gets loaded automatically if I don't use the forName() method?
DriverManager asks for all implementations of java.sql.Driver. The ServiceLoader mechanism will look at all META-INF/services/java.sql.Driver resources. This means it searches all JAR files on the class path for files with this name. It will try to instantiate the classes inside these files. This will cause the SQL drivers to register themselves at DriverManager.