According to this tutorial, calling Class.forName isn’t needed anymore with JDBC 4.0+ drivers. I successfully followed the method in the example (just calling DriverManager.getConnection) for a stand-alone program using MySQL, but when I tried to connect to the exact same database from a class that was part of a web app running on Tomcat 7, it wouldn’t work; instead I got a No suitable driver found exception.
The mysql-connector-java-5.1.18-bin.jar file was in tomcat\webapps\DatabaseProject\WEB-INF\lib, I triple checked, but it wasn’t working, so I started trying things. I added a call to Class.forName and it worked. That was the only thing that changed.
Anyway my question is, does anybody know why this worked or what was going on here? My only theory is that I also have hsqldb.jar in tomcat\lib for another project and maybe somehow the drivers got confused? But I was under the impression that DriverManager is supposed to be able to tell automatically which driver to use, so that’s not supposed to be an issue… Anyway if someone could enlighten me as to what’s going on here, I’d really appreciate it.
JDBC4 drivers include a file:
META-INF/services/java.sql.Driverin the jar which uses the ServiceProvider mechanism to register the Driver implementation with the JVM (see javadocs for java.util.ServiceLoader). That’s why
Class.forNameis no longer necessary.My guess is that this is a class loader issue. The
ServiceLoaderjavadoc mentions that:I would try putting your driver in the
tomcat\libdirectory rather than your web app directory to see if that makes a difference (different class loader?).If you launch your web app through an ide and set a breakpoint, once you hit the breakpoint, you can use the “evaluate expression” feature to execute:
ServiceLoader.load(Driver.class). This will give you aServiceLoaderclass which you can peek into to see which Drivers are registered. You can check if the mysql driver is there, where in the list it is, etc, which might help in figuring out the behaviour here.