1

Every time I open a connection to mysql database to perform some query I have to put this code before:

    Class.forName("com.mysql.cj.jdbc.Driver");

otherwise I got this error:

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

Example:

        Class.forName("com.mysql.cj.jdbc.Driver");

        try (Connection conn = DriverManager.getConnection(Data.URL.getValue(), Data.USER.getValue(), Data.PASS.getValue())) {
        DSLContext create = DSL.using(conn, SQLDialect.MYSQL);

My j-connector jar is in the web-inf lib forlder already. Do I really have to load the drivers explicitally every time or there is a better way to do this?

poldoj
  • 137
  • 1
  • 10
  • You have to load the driver **once** when the application starts. In a web application (at least on Tomcat), drivers located inside the WAR are not loaded automatically, you would need to put the driver in the `tomcat/lib` folder for automatic driver loading to work. As an aside, it is recommended to use a `DataSource` (preferably backed by a connection pool) in a web application. – Mark Rotteveel May 01 '23 at 09:36

1 Answers1

3

Place the MySQL JDBC driver jar in the WEB-INF/lib folder of your web application. Then register the driver with the DriverManager once during the initialization of your application, for example, in a servlet context listener.

Here's an example of how to register the driver:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.DriverManager;
import java.sql.SQLException;

public class CustomServletContextListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        try {
            //make sure that the class exists (should work like that, not 100% sure)
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Could not load JDBC driver class", e);
        }

        try {
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        } catch (SQLException e) {
            throw new IllegalStateException("Could not register JDBC driver", e);
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
        // cleanup stuff
    }
}
JavaMan
  • 1,142
  • 12
  • 22
  • It worked, the only thing I was missing again was this line: my.package.CustomServletContextListener/listener> in my web-inf, thank you – poldoj May 01 '23 at 08:27