首页 > 解决方案 > 找不到带有 VSCode 类的 JDBC

问题描述

通过添加“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);

感谢您的任何帮助

库添加 错误

标签: javamysqljdbcvisual-studio-codeconnection

解决方案


根据文档,类名应该是com.mysql.cj.jdbc.Driver而不是com.mysql.jdbc.Driver. getDeclaredConstructor()此外,似乎没有必要调用 to 。也许这些是你问题的根源。


推荐阅读