mysql执行jar,执行JAR时java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

I am attempting to connect to my local MySQL server with the following code:

dbURL = "jdbc:mysql://localhost:3306:/" + dbname;

try{

Class.forName("com.mysql.jdbc.Driver");

try{

con = DriverManager.getConnection(dbURL, dbuser, dbpass);

} catch (SQLException ex){

System.out.println("ERROR: Could not connection to SQL DB");

con = null;

}

} catch (ClassNotFoundException e){

System.out.println("Error: ");

e.printStackTrace();

}

I then get

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I understand that Java cannot find the proper driver for connecting the Java environment to the MySQL database. This is being compiled on a Windows 7 system and ported over to an Ubuntu 11.04 system.

Is there a particular way I can run the Java program with a particular classpath such as:

java -cp /usr/share/java/mysql-connector-java.jar program.jar

That didn't work when I tried it.

解决方案

In case of JARs, the -cp and -classpath arguments and the %CLASSPATH% environment variable are ignored. Instead, the classpath has to be specified in the Class-Path entry of JAR's own /META-INF/MANIFEST.MF file. It can be a path relative to the JAR itself. E.g. in the same folder or in a /lib subfolder.

The below example assumes the driver to be in the same folder as the JAR.

Class-Path: mysql-connector-java.jar

(make sure that the MANIFEST.MF file has a blank line at the end)

See also:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值