繁体   English   中英

JDBC 驱动程序错误,无法连接到 mysql 服务器

[英]JDBC driver error and cannot connect to mysql server

当我运行我的代码尝试连接到 sql 服务器时,我不断收到错误消息

Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:375)

这是我的代码。 我确保将连接器/J 添加到类路径中,但仍然没有变化

import java.sql.*;

public class App {
    
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/vehicle", "root", "root"); // For MySQL only

        vehicle focus = new vehicle("Ford", "Focus", 200, 2004, 3000);

        System.out.println(focus.getMake());
    }
}

首先,不需要使用Class.forName加载 JDBC 驱动程序,因为JDBC 4.0 于 2006 年提供,将由服务提供程序寄存器加载(服务驱动程序寄存器)

只需删除此行,它应该可以工作。 如果您需要 class 名称,最好查阅 Connector/J 的文档 Take care to read the docs for the correct driver version because the class name changed (currently it's com.mysql.cj.jdbc.Driver).

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM