"No suitable driver found" in Java database connection

4
Well, I use eclipse and I'm trying to connect to a MySQL database with my project, my code, compared to other tutorials I found, is perfect, and that's it:

package pack;

import java.sql.*;

import javax.swing.JOptionPane;


public class Banco {

public Statement stm;
public ResultSet rs;
public Connection conn;
public String Driver = "com.mysql.jdbc.Driver";

public void Conecta(){
    System.setProperty("jdbc.Drivers", Driver);
    try {
        conn = DriverManager.getConnection("jdbc:mysql:meu_caminho", "meu_login", "minha_senha");
        JOptionPane.showMessageDialog(null, "Conectado!");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "Erro!" + "\n" + e.getMessage());
    }
}

public void Desconecta(){
    try {
        conn.close();
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "Erro ao fechar!");
    }
}

}

The problem is that it gives the error "No suitable driver found for my_path"

The solution that everyone says is that I have to put the jdbc driver in my project, I tried to download the mysql site itself the java connector, however it is an msi file, and what all the tutorials say is to put .jar, but I can not find this jar at all, the only one I found was a 4shared link, a version 5.1.13 in .jar, but even after I add the library, the same error continues .. .

Does anyone know where I can get this .jar?

  • is there "com.mysql.jdbc.Driver" and yet, it does NOT connect ...

        
  • asked by anonymous 10.06.2014 / 01:49

    1 answer

    6

    You need to load the com.mysql.jdbc.Driver class. Example:

    public void Conecta(){
        //System.setProperty("jdbc.Drivers", Driver);
        try {
            Class.forName("com.mysql.jdbc.Driver"); //adicione essa linha
            conn = DriverManager.getConnection("jdbc:mysql:meu_caminho", "meu_login", "minha_senha");
            JOptionPane.showMessageDialog(null, "Conectado!");
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Erro!" + "\n" + e.getMessage());
        }
    }
    

    Class.forName () causes the class passed as an argument to dynamically load the class calling it. And your error rightly accuses the lack of the appropriate Driver.

    I do not know exactly what System.setProperty("jdbc.Drivers", Driver); does, but it looks like it was a failed attempt to add the Driver class, comment on that line and add the line I indicated above.

        
    10.06.2014 / 02:05