If I want to connect to database I should write code like this:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/mysidorservicename", "sysdba", "password123");
Why should I load the concrete driver before I connect to database? The result of the Class.forName statement is ignored - the loaded class is obviously not associated with the DriverManager. Can I just load all drivers used for different databases in moment of start application and will not write Class.forName code before each connection?
Older DriverManager implementations (before JDBC 4.0, which was park of JDK 6), required drivers to have a static block that would register them to the DriverManager. Static blocks are called once when the class is loaded by the driver manager. To your question - it doesn't really matter where you load these classes, as long as you load the drivers before attempting to use them.
Since JDBC 4.0 (which is, as mentioned above, a part of JDK 6), you don't have to call Class.forName at all, though. To quote the DriverManager's javadoc:
The
DriverManagermethodsgetConnectionandgetDrivershave been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry [etc..]
In layman's words, it's up to the driver to register itself to declare it provides a JDBC service for a given connection string, and you can just remove the Class.forName calls from your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With