java 找不到mysql驱动_Java类路径找不到MySQL驱动程序

bd96500e110b49cbb3cd949968f18be7.png

Whenever I run the following code:

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");

...

}

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

Classpath:

...

/C:/myProjectDir/

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

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

Any thoughts?

解决方案

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.

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

For class files in an unnamed package, you include the directory that contains the class files

For class files in a named package, you include the directory that contains the root package, which is the first package in the full package name

For a JAR or zip file that contains class files, you include the name of the zip or JAR file

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

...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值