我正在尝试使用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
答案 0 :(得分:2)
看起来您还没有在项目中配置JDBC驱动程序。确保在运行之前将其添加到类路径中(通过命令行或基于IDE)。
答案 1 :(得分:1)