java.lang.ClassNotFoundException: com.mysql.jdbc.Driver 执行 JAR 时 [英] 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
当我尝试时,这不起作用.
That didn't work when I tried it.
推荐答案
对于 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)
这篇关于java.lang.ClassNotFoundException: com.mysql.jdbc.Driver 执行 JAR 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!