Question:
Well, I use eclipse and I'm trying to connect a MySQL database with my project, my code, compared to other tutorials I found, is perfect, and this is 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 java connector from the Mysql website, however it is an msi file, and what all the tutorials say is to put the .jar , but I can't find this jar at all, the only one I found was in a 4shared link, a 5.1.13 version in .jar, but even after I add the library, the same error keeps on giving…
Does anyone know where I can get this .jar?
Note: about this .jar that I found, I put it in the project, I clicked the right button, I went to properties, java build path, I added the .jar, the Referenced libraries folder was created, and when I open it, the "com.mysql.jdbc.Driver" and yet it does NOT connect…
Answer:
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 that calls it. And your error justifies the lack of the appropriate Driver.
I don't know exactly what the System.setProperty("jdbc.Drivers", Driver);
does, but it looks like it was a failed attempt to add the Driver class, comment out that line and add the line I indicated above.