1

I am having a simple dynamic web project in Eclipse. I've added the mysql-connector under WEB-INF/lib and then added to build path. It seems strange to me, that as long as I run my project as Java Application, the driver is loaded correctly and everything works fine. But when I deploy the project to Tomcat, it starts throwing SQLException saying No suitable driver found for jdbc:mysql://..... When I add it explicitly using Class.forName("com.mysql.cj.jdbc.Driver"); it works.

I tried to debug it and indeed no drivers are loaded when the project is deployed, but everything is loaded correctly, when running locally.

Could somebody exaplain that to me?

  • According to Tomcat's documentation, it's because of how (a) Tomcat's [class loaders](http://tomcat.apache.org/tomcat-9.0-doc/class-loader-howto.html) are arranged, and (b) how Tomcat tries to avoid perceived issues with the Java SPI mechanism (as used by modern JDBC drivers): [DriverManager, the service provider mechanism and memory leaks](http://tomcat.apache.org/tomcat-9.0-doc/jndi-datasource-examples-howto.html#DriverManager,_the_service_provider_mechanism_and_memory_leaks). – andrewJames Jul 01 '21 at 21:15
  • That section from (b) concludes: "_Thus, the web applications that have database drivers in their WEB-INF/lib directory cannot rely on the service provider mechanism and should register the drivers explicitly._". I am leaving these as comments because I don't know if this (probably quite old) documentation is correct. Maybe the SO community can clarify? – andrewJames Jul 01 '21 at 21:15
  • You really should not use `DriverManager` directly in a web application. Use a proper connection pool to manage connections for your. – Mark Rotteveel Jul 02 '21 at 11:44

0 Answers0