When is Class.forName required when connecting to a database via JDBC in a web application?

According to this tutorial , the call is Class.forNameno longer needed by JDBC 4.0+ drivers. I successfully executed the method in the example (just calling DriverManager.getConnection) for a stand-alone program using MySQL, but when I tried to connect to the same database from a class that was part of a web application running on Tomcat 7, this would not work; instead, I got an exception No suitable driver found.

The file mysql-connector-java-5.1.18-bin.jarwas in tomcat\webapps\DatabaseProject\WEB-INF\lib, I checked it three times, but it did not work, so I started trying. I added a challenge Class.forNameand it worked. This is the only thing that has changed.

Anyway, my question is: does anyone know why this worked or what happens here? My only theory is that I also have hsqldb.jarin tomcat\libfor another project and maybe the drivers got messed up somehow? But I had the impression that the DriverManager should be able to automatically tell which driver to use so that this is not a problem ... Anyway, if someone could enlighten me about what is happening here, I would really appreciate he.

+3
source share
1 answer

JDBC4 drivers contain the file:

META-INF/services/java.sql.Driver

, ServiceProvider JVM (. javadocs java.util.ServiceLoader). Class.forName .

, . ServiceLoader javadoc , :

, ; , , .

tomcat\lib, -, , ( ?).

- , , " " : ServiceLoader.load(Driver.class). ServiceLoader, , , . , mysql, , .., .

+3

All Articles