JDBC Class.forName vs DriverManager.registerDriver

JavaJdbc

Java Problem Overview


Which is the difference from forName method vs registerDriver to load and register a JDBC driver?

Java Solutions


Solution 1 - Java

Class.forName() is not directly related to JDBC at all. It simply loads a class.

Most JDBC Driver classes register themselves in their static initializers by calling registerDriver().

registerDriver() is the real call that you hardly ever need to call yourself (unless you write your own JDBC driver).

Note that in JDBC 4 you should not need either of those if your JDBC driver is up-to-date, as drivers can be found using the service location mechanisms instead (i.e. simply leave out that call and open your connection as usual). See the documentaton of DriverManager for details:

> The DriverManager methods getConnection and getDrivers have 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: > > my.sql.Driver > > 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.

Solution 2 - Java

Never call DriverManager.registerDriver() method manually. The JDBC spec requires a driver to register itself when the class is loaded, and the class is loaded via Class.forName(). In JDBC 4 the drivers are able to be loaded automatically just by being on the class path.

DriverManager.registerDriver() manually is potentially dangerous since it actually causes the Driver to be registered twice. If your code requires you to deregister a Driver to prevent a memory leak then you would only end up deregistering it once and leave a second instance registered.

Solution 3 - Java

In additaion to what Joachim Sauer already mentioned about JDBC 4 drivers, note that in practice you usually want to inject either an EntityManager (JPA) or a pooled DataSource (and use JdbcTemplate of Spring).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionxdevel2000View Question on Stackoverflow
Solution 1 - JavaJoachim SauerView Answer on Stackoverflow
Solution 2 - JavaDavid O'MearaView Answer on Stackoverflow
Solution 3 - JavaPuceView Answer on Stackoverflow