1
votes

I have problem with connecting my Maven web project to MySQL database in Netbeans. Every time when I am trying to connect it is throwing

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

I have added mysql-connector-java version 5.1.38 dependency to pom.xml file. Then I have added mysql-connector-java-5.1.38-bin.jar to $CATALINA_HOME /lib folder. The folder WEB-INF/lib contains same .jar file. If I am trying to do

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

my project is connecting to DB without any exceptions.

Below my Servlet method connects to MySQL database

public void connectToDB(){


    try{
        String URL = "jdbc:mysql://localhost:3306/Store";
        String username = "root";
        String password = "sesame";

        Connection connection = DriverManager.getConnection(URL, username, password);
        System.out.println("DB has been connected!!!!!!!!!!!!!!!!!!");
    }catch(SQLException ex){
        for(Throwable t : ex){
            t.printStackTrace();
        }
    }
}

The URL variable (port number and hostname) is correct. The problem is JDBC driver wasn't autoloaded at all.

I have searched through most of questions here but didn't find anything helpful.

2

2 Answers

1
votes

In my case, Mac with Catalina OS, mysql-connector-java-8.0.19.jar and NetBeans project using Maven, I needed to load the class for com.mysql.cj.jdbc.Driver rather than com.mysql.jdbc.Driver. Note the "cj".

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

had to precede the SQL driver connect request. I don't know fully why since it is my understanding that after JDBC 4.0, no SQL driver class needed to be pre-loaded.

0
votes

you should add this part as well

public void connectToDB(){


    try{
        String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        String URL = "jdbc:mysql://localhost:3306/Store";
        String username = "root";
        String password = "sesame";

        Class.forName(JDBC_DRIVER);
        Connection connection = DriverManager.getConnection(URL, username, password);
        System.out.println("DB has been connected!!!!!!!!!!!!!!!!!!");
    }catch(SQLException ex){
        for(Throwable t : ex){
            t.printStackTrace();
        }
    }
}