2012-05-15 28 views
2

我已經將我的mysql-connector-java-5.1.18-bin.jar添加到jre和jdk庫。而這裏它是:java.lang.ClassNotFoundException:com.mysql.jdbc.Driver(在jre的庫中)

C:\Windows\system32>javap java.io.Bits 
    Compiled from "Bits.java" 
    class java.io.Bits extends java.lang.Object{ 
     java.io.Bits(); 
     static boolean getBoolean(byte[], int); 
     static char getChar(byte[], int); 
     static short getShort(byte[], int); 
     static int getInt(byte[], int); 
     static float getFloat(byte[], int); 
     static long getLong(byte[], int); 
     static double getDouble(byte[], int); 
     static void putBoolean(byte[], int, boolean); 
     static void putChar(byte[], int, char); 
     static void putShort(byte[], int, short); 
     static void putInt(byte[], int, int); 
     static void putFloat(byte[], int, float); 
     static void putLong(byte[], int, long); 
     static void putDouble(byte[], int, double); 
    } 


    C:\Windows\system32>javap com.mysql.jdbc.Driver 
    ERROR:Could not find com.mysql.jdbc.Driver 

但是,當我顯示一個直接的類路徑到同一個文件,它是好的。

C:\Windows\system32>javap -classpath "B:\Java\Tools\mysql-connector-java-5.1.18\ 
mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar" com.mysql.jdbc. 
Driver 
Compiled from "Driver.java" 
public class com.mysql.jdbc.Driver extends com.mysql.jdbc.NonRegisteringDriver i 
mplements java.sql.Driver{ 
    public com.mysql.jdbc.Driver()  throws java.sql.SQLException; 
    static {}; 
} 

的問題我是用Thilo's answer時動態加載的驅動程序啓動。沒有IOException。但字符串Class.forName(driver).newInstance()我有ClassNotFoundException異常。將jar添加到jre後,沒有任何改變。那有什麼問題?

回答

1

究竟是什麼意思添加jar後jre?我擔心mysql-connector-java-5.1.18-bin.jar未正確添加到類路徑中。 ClassNotFoundException僅當該類不存在於可搜索類路徑中時纔會引發。所有JDK附帶的jar都是引導類,可供java加載。但是,所有第三方類都需要設置在可搜索的系統或應用程序級別類路徑中,以便java可以加載指定的類參數。

在命令提示符處嘗試以下命令並執行您的java類。

set mysqljar="absolute-path-to\mysql-connector-java-5.1.18-bin.jar" 
set classpath=%classpath%;.;%mysqljar% 

只要這個jar在可搜索的類路徑中可用,所有的類加載器都可以從jar中找到並加載類。試試這個改變並運行Thilo的例子,它應該工作。

read more on class paths, for command line, here

0

如果您要從命令行編譯代碼,請使用選項來請求javac使用mysql驅動程序jar。像下面的東西應該工作:

C:\MyProject>javac -cp "B:\Java\Tools\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar" MyClass.java 
相關問題