java.lang.ClassNotFoundException: com.mysql.jdbc.Driver 错误即使在导入库后

Muh*_*Haq 7 java mysql database eclipse jdbc

我已经导入了我的库“mysql-connector-java-5.1.39”,正如大多数人回答的完全相同的问题,但我仍然收到此错误

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Run Code Online (Sandbox Code Playgroud)

这是测试类的代码

package database;

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {

    public static void main(String[] args) throws Exception {
        getConnection();
    }

    public static Connection getConnection() throws Exception {
        try{
            String driver="com.mysql.jdbc.Driver";
            String url="jdbc:mysql://localhost:3306/test";
            String username="root";
            String password="root";
            Class.forName(driver);
            Connection conn= DriverManager.getConnection(url,username,password);
            System.out.println("connected");
            return conn;
        }
        catch (Exception e){
            System.out.println(e);
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

日食目录

使用 mac 操作系统。

Ste*_*n C 5

大家跟着我重复一遍。(:-))

“java.lang.ClassNotFoundException: com.mysql.jdbc.Driver”不是编译错误。

因此,更改 >>build<< 路径或添加import无法解决问题。

解决方案是确保运行应用程序时 JAR 文件位于类路径上。例如,如果您的测试类位于bin\database\Main.class并且驱动程序 JAR 位于lib...

$ java -classpath bin:lib/mysql-connector-java-5.1.39.jar database.Main
Run Code Online (Sandbox Code Playgroud)