我在使用 VS Code 创建 Java 项目并添加“mysql-connector-java-8.0.21.jar”时遇到严重问题。 我已完成以下步骤:
我尝试使用 jdk 11 和 15(不是 8,因为 VS Code 不再支持它)
启动我的代码会导致错误:
java.lang.ClassNotFoundException: com.mysql.cj.LocalizedErrorMessages
这是我的代码的摘录:
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SimpleJDBCApplication {
static final String DB_URL = "jdbc:mysql://localhost:3306/company";
static final String DB_DRV = "com.mysql.jdbc.Driver";
static final String DB_USER = "root";
static final String DB_PASSWD = "";
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try{
/*To connect with a database using JDBC you need to select get the
driver for the respective database and register the driver.
The forName() method of the class named Class accepts a class name
as a String parameter and loads it into the memory, Soon the is
loaded into the memory it gets registered automatically */
//Take new instance
System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance();
connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);
statement=connection.createStatement();
resultSet=statement.executeQuery ("SELECT * FROM dept");
while(resultSet.next()){
System.out.printf("%d\t%s\t%s\n",
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3));
错误发生在
connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);
行
感谢您的帮助
1.适用于MySQL 8.0以下版本:
静态最终字符串 DB_URL = "jdbc:mysql://localhost:3306/company";
更改为
static final String DB_URL ="jdbc:mysql://localhost:3306/company?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
2.将
com.mysql.jdbc.Driver
转移到com.mysql.cj.jdbc.Driver
;
3.
Class.forName("com.mysql.cj.jdbc.Driver")
就够了,也有这段代码,System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver")
不需要,可以评论或删除;
这对我有用,你可以尝试一下。
根据文档,类名应该是
com.mysql.cj.jdbc.Driver
而不是com.mysql.jdbc.Driver
。另外,对 getDeclaredConstructor()
的调用似乎是不必要的。也许这些就是你问题的根源。
步骤1)从VS Code左下角打开java项目
第 2 步)单击引用库上的 + 按钮
步骤 3) 浏览驱动程序,即本例中的连接器文件。
第 4 步)问题解决并创建连接