"No suitable driver found" in database connection in Java
Well, I use eclipse and I'm trying to connect a MySQL database with my project, my code, compared to other tutorials I found, it's 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 of"No suitable driver found for my_way"
The solution that everyone says is that I have to put the JDBC driver in my project, I tried to download on the MySQL site the Java connector, but it is an msi file, and what all the tutorials say are to put the .jar, but I can't find this jar at all, the only one I found was a link from 4shared, a version 5.1.13 in .jar, but even after I add the library, the same error keeps giving...
Someone knows where I can get this one .jar?
Note: about that .jar I found, I put it in the project, right-clicked, went into properties, java build path, added the .jar, was created the referenced libraries folder, and when I open it, is there the " com.mysql.jdbc.Driver " and yet yes, it does not connect...
1 answers
You need to load the class with.mysql.jdbc.Driver. 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 argument to be dynamically loaded to the class calling it. And your mistake rightly accuses the lack of the appropriate Driver.
I don't know exactly what System.setProperty("jdbc.Drivers", Driver);
does, but it looks like it was a failed attempt to add the driver class, comment this line and add the line I indicated above.