Java类路径找不到MySQL驱动程序

Java类路径找不到MySQL驱动程序

本文介绍了Java类路径找不到MySQL驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我运行以下代码:

import com.mysql.jdbc.Driver;

public void insertIntoMysql() {

    // Print out classloader information
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    String urlStr = "";
    for (int i=0; i < urls.length; i++) {
       urlStr += urls[i].getFile() + "\n";
    }
    System.out.println("Classpath:\n" + urlStr);

    // connect to mysql
    Class.forName("com.mysql.jdbc.Driver");
    String myUrl = "jdbc:mysql://localhost:3306/Compass";
    Connection conn = DriverManager.getConnection(myUrl, "root", "newpoint");

    ...
}

我在Class.forName行上收到"ClassNotFoundException:com.mysql.jdbc.Driver"错误.但是,我的类路径打印为:

I get a "ClassNotFoundException: com.mysql.jdbc.Driver" error on the Class.forName line. However, my classpath prints out as:

Classpath:
...
/C:/myProjectDir/

我的类路径中有以下jar"/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar".

and I have the following jar "/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar" within my classpath.

我已重新启动程序,以防万一ClassLoader在程序启动时正在加载所有内容,但我一直收到该错误.

I've restarted the program just in case the ClassLoader is loading everything when the program starts, but I keep getting that error.

有什么想法吗?

推荐答案

当前看来,您仅在类路径上拥有项目目录,而没有mysql-connector-java-5.0.8-bin.jar文件本身

Currently it looks like you only have your project directory on your class path, and not the mysql-connector-java-5.0.8-bin.jar file itself.

在Java中,关于在类路径中包括什么的规则如下:

In Java, the rules for what to include on the classpath are as follows:

要获取mysql驱动程序,您需要按名称将驱动程序jar添加到类路径:

To pick up the mysql driver, you'll need to add the driver jar to the class path by name:

Classpath:
...
/C:/myProjectDir/
/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar
...

有关更多信息,请查看有关PATH的Java教程和CLASSPATH ,以及设置班级路径.

For more information, take a look at the Java tutorial on PATH and CLASSPATH, and the Oracle documentation on Setting the Class Path.

这篇关于Java类路径找不到MySQL驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:36