How to correct the "SQLException: No suitable driver found" error when making a connection?

2

I'm trying to connect to the database in my code, however it appears the following error:

  

Exception in thread "main" java.sql.SQLException:
  No suitable driver found for jdbc: mysql: // localhost: 3306 / user

Code:

public class ConexaoBd {
    public static void main(String[] args) throws SQLException{
        Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuario","root","tonhaoroot");

        conexao.close();    
    }
}
    
asked by anonymous 25.09.2015 / 06:59

1 answer

5

Before creating the connection you need to register the mysql driver. It will look like this:

public class ConexaoBd {
    public static void main(String[] args) throws SQLException{
        Class.forName("com.mysql.jdbc.Driver"); /* Aqui registra */
        Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuario","root","tonhaoroot");

        conexao.close();    
    }
}

Also check that the mysql (.jar) driver is in the application's classpath.

    
25.09.2015 / 13:07