3

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.

Maltiriel
  • 793
  • 2
  • 11
  • 28

1 Answers1

3

JDBC4 drivers include a file:

META-INF/services/java.sql.Driver

in 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.forName is no longer necessary.

My guess is that this is a class loader issue. The ServiceLoader javadoc mentions that:

The provider must be accessible from the same class loader that was initially queried to locate the configuration file; note that this is not necessarily the class loader from which the file was actually loaded.

I would try putting your driver in the tomcat\lib directory 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 a ServiceLoader class 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.

Glenn
  • 8,932
  • 2
  • 41
  • 54
  • I just saw this, thanks so much for answering! I really appreciate it. I'll try this later and see if it will help me pinpoint the issue. – Maltiriel Feb 01 '12 at 23:05