java - 找不到带有 VSCode 类的 JDBC
问题描述
通过添加“mysql-connector-java-8.0.21.jar”,我在使用 VS Code 创建 Java 项目时遇到了严重问题。我已完成以下步骤:
- 从命令行使用 VS Code 创建一个新的 Java 项目
- 通过执行“添加引用的库”添加 mysql 连接器。
我尝试同时使用 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);
感谢您的任何帮助
解决方案
根据文档,类名应该是com.mysql.cj.jdbc.Driver
而不是com.mysql.jdbc.Driver
. getDeclaredConstructor()
此外,似乎没有必要调用 to 。也许这些是你问题的根源。
推荐阅读
- umbraco - Umbraco:检查页面是否标记为受保护并重定向到登录
- azure - 服务总线的 Azure 函数绑定
- csv - 如何在 SOLR 中加入文档
- php - PHP 无法执行创建的命令,但 exec() 和 system() 工作正常
- php - 尝试启动 MySQL 应用程序
- r - R 绘制运行执行时间与不同输入值的关系
- haskell - 如何使用 monad 随机播放列表?
- javascript - 如何获取 HTML 标签内的值并将其绑定到 aurelia 中的 ts(组件文件)
- javascript - 如何使用 Javascript 在上午 9:00 到上午 10:00 之间运行代码?
- excel - Excel公式获取第n行的表值