JDBC VSCode class 未找到

JDBC with VSCode class not found

我在添加“mysql-connector-java-8.0.21.jar”时遇到严重问题,无法使用 VS Code 创建 Java 项目。 我已完成以下步骤:

我尝试同时使用 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);

感谢您的帮助

Library added Error

根据 documentation,class 名称应为 com.mysql.cj.jdbc.Driver 而不是 com.mysql.jdbc.Driver。此外,对 getDeclaredConstructor() 的调用似乎是不必要的。也许这些是您问题的根源。

1.This适用于MySQL8.0以下版本:

static final String DB_URL = "jdbc:mysql://localhost:3306/company";

改为

static final String DB_URL ="jdbc:mysql://localhost:3306/company?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"

2.Transfer com.mysql.jdbc.Drivercom.mysql.cj.jdbc.Driver;

3.Class.forName("com.mysql.cj.jdbc.Driver")就够了,还有这段代码,System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver")不需要,可以评论或删除;

这个对我有用,你可以试试。

在 VSCode 的 left-hand 侧的资源管理器选项卡中单击 Java 项目。然后 right-click 在您的项目名称上并单击 Configure Classpath。这将在新选项卡中打开类路径配置。滚动到底部,然后单击引用库上的添加。这将打开一个资源管理器 pop-up window。 Select java-mysql 连接器 jar 文件,然后它应该可以工作。

步骤 1) 从 VS Code

左下角打开 java 个项目

步骤 2) 在引用的库上单击 + 按钮

步骤 3) 浏览驱动程序,即本例中的连接器文件。

第 4 步)问题已解决并已创建连接