如何在Java中连接MySQL数据库?
当我尝试时,我得到
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Or
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
HOW
设置驱动程序以运行快速示例
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J
2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:
No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development
java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
要设置CLASSPATH
方法1:设置CLASSPATH变量。
export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile
在上面的命令中,我已经将CLASSPATH设置为当前文件夹和mysql-connector-java-VERSION.jar文件。因此,当执行java MyClassFile命令时,java应用程序启动器将尝试加载CLASSPATH中的所有java类。
它发现Drive class => BOOM错误消失了。
方法2:
java -cp .:mysql-connector-java-VERSION.jar MyClassFile
注意:forname(“com.mysql.jdbc.Driver”);目前已弃用2019年4月1日。
希望这能帮助到一些人!
简短而甜蜜的代码。
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
//Database Name - testDB, Username - "root", Password - ""
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
SQL server 2012
try {
String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
//KHILAN is Host and 1433 is port number
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection(url);
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}