执行JAR时java.lang.ClassNotFoundException:com.mysql.jdbc.Driver [英] java.lang.ClassNotFoundException: com.mysql.jdbc.Driver when executing JAR
问题描述
我正在尝试使用以下代码连接到我的本地MySQL服务器:
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();
}
然后我得到
java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
我明白Java不能找到将Java环境连接到MySQL数据库的正确驱动程序。这是在Windows 7系统上编译并移植到Ubuntu 11.04系统。
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.
我是否有一种特殊的方式可以运行具有特定类路径的Java程序,例如:
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
我试用时没用。
推荐答案
对于JAR, -cp
和 -classpath
参数和%CLASSPATH%
环境变量被忽略。相反,必须在JAR自己的 /META-INF/MANIFEST.MF
Class-Path 条目中指定类路径。 >文件。它可以是相对于JAR本身的路径。例如。在同一文件夹或 / lib
子文件夹中。
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.
以下示例假设驱动程序位于同一文件夹中作为JAR的文件夹。
The below example assumes the driver to be in the same folder as the JAR.
Class-Path: mysql-connector-java.jar
(确保 MANIFEST.MF
文件末尾有一个空行)
(make sure that the MANIFEST.MF
file has a blank line at the end)
- 使用JAR文件 - 基础知识 - 了解MANIFEST.MF
- Eclipse:Package多个项目合并为一个JAR
- Java清单文件的类路径以及它如何确定相对目标
- Using JAR files - The Basics - Understanding the MANIFEST.MF
- Eclipse: Package multiple projects into one JAR
- Java Manifest file's class path and how it determines relative dirs
这篇关于执行JAR时java.lang.ClassNotFoundException:com.mysql.jdbc.Driver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!