我正在尝试使用 JDBC 通过 Java 建立与 MySQL 数据库的连接。
但是当我尝试这样做时,我遇到了一些错误。 我确定问题不是因为 MySQL 服务器设置错误,因为我尝试连接 MySQL Workbench,并且这有效。
我使用这段 Java 代码来设置 de JDBC 连接:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnection {
public static SQLConnection instance = new SQLConnection();
public static String URL = "jdbc:mysql://localhost:3306/canbusdata";
public static String USER= "root";
public static String PSW = "root";
public SQLConnection()
{
}
public static Connection getConnection() {
System.out.println("-------- MySQL JDBC Connection ------------\n");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(URL,USER,PSW);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console: \n");
e.printStackTrace();
}
return connection;
}
}
但是我得到这个错误:
-------- MySQL JDBC Connection ------------
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Where is your MySQL JDBC Driver?
MySQL JDBC Driver Registered!
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
Connection Failed! Check output console:
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at SQLConnection.getConnection(SQLConnection.java:21)
at Start.ProcessData(Start.java:109)
at Start.main(Start.java:21)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/canbusdata
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at SQLConnection.getConnection(SQLConnection.java:31)
at Start.ProcessData(Start.java:109)
at Start.main(Start.java:21)
Exception in thread "main" java.lang.NullPointerException
at Start.ProcessData(Start.java:110)
at Start.main(Start.java:21)
Java Result: 1
最佳答案
看起来您还没有在项目中配置 JDBC 驱动程序。确保在运行它之前将它添加到类路径中(通过命令行或基于 IDE)。
关于java无法连接到jdbc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23272500/