简体   繁体   中英

Is Driver registering by `Class.forName()` needed in mysql-connector 8.0?

I already know from on JDBC 4.0. and JDK 6 , drivers those are found in classpath are automatically loaded. This is the reason we are used to ignoring that Class.forName(dbDriver); line of code when creating JDBC connection.

But recently I installed MySQL Server 8.0.11 and I updated the driver to mysql-connector-java:8.0.11 in my simple Servlet project that runs on tomcat 8.5.30 . But it gives me the infamous exception

java.sql.SQLException: No suitable driver found for 
jdbc:mysql://localhost:3306/mysql at ...

But all my code was working and fine before. So then I added the Class.forName("com.mysql.jdbc.Driver");

And it works. I think I didn't miss anything. Can anyone explain to me what it might be the reason?

The JDBC 4.0 (and higher) automatic driver loading works only if the driver jar is on the initial (system) class path of the application. If you are using Tomcat, the driver would have to be in the <catalina-home>/lib folder.

If you deploy the driver together with your application, then the driver is on the context classpath of that specific application, and it will need to be explicitly loaded using Class.forName .

But in practice, you should not be using DriverManager.getConnection to create connections in a web application. You should be using a data source (preferably with connection pooling), either created and initialized in code, or in the context or server configuration of Tomcat. In that case this problem wouldn't even surface, because either the data source already knows how to get the driver, or you have to explicitly configure it with the driver to use anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM