2012-05-28 34 views
2

我目前正在需要加載mysql驅動運行時並使用java連接到數據庫的需求。加載並連接到mysql jdbc驅動運行時

我使用URLClassLoader加載jar文件

File f = new File("D:/Pallavi/workspace/WarInstallation/mysql-connector-java-5.0.4-bin.jar"); //Jar path 

URLClassLoader urlCl = new URLClassLoader(new URL[] { f.toURL()},System.class.getClassLoader()); 
Class sqldriver = urlCl.loadClass("com.mysql.jdbc.Driver"); // Runtime loading 

Driver ds = (Driver) sqldriver.newInstance(); //Compilation failing as "sqldriver" class of type Driver is not found 

//I am using now java.sql.Driver to remove the compilation error 

sqldriver = Class.forName("com.mysql.jdbc.Driver", true, sqldriver.getClassLoader()).newInstance(); //Runtime fail.. "Driver" Class not Found Exception. 

雖然類加載罰款,我不能建立數據庫連接(中找不到合適的驅動程序...)不管我的驅動程序。

請建議加載jdbc「com.mysql.jdbc.Driver」類運行時的方法。 讓我知道,如果您需要任何進一步的信息,因爲這是迫切的。

在此先感謝。

+0

你有沒有在classpath mysql的罐子? –

+0

你好,我已經在環境變量中設置了mysql jar的類路徑,我們是否需要通過系統屬性來設置它? – Pallavi

回答

0

DriverManager忽略在運行時加載的類,它只對System加載器加載的類有效。

您可以創建一個虛擬驅動程序類來封裝您的實際數據庫驅動程序。源代碼可以找到here

題外話:

File.toURL已被棄用,而不是從使用toURLFileURI

URLClassLoader urlCl = new URLClassLoader(new URL[] { f.toURI().toURL()},System.class.getClassLoader()); 
1

獲取URL我有三個問題之前,我回答你的問題:

  1. 聲明1

    ya, I have set the classpath of mysql jar in the environment variables, do we need to set it through system properties?

    Q1:爲什麼是依靠自定義類加載器,當一個類是現成的,從類路徑系統類加載器?
    您不需要明確的類路徑mysql***.jar來使用自定義類加載器。

  2. 聲明2

    Class sqldriver = urlCl.loadClass("com.mysql.jdbc.Driver"); // Runtime loading
    //Compilation failing as "sqldriver" class of type Driver is not found
    Driver ds = (Driver) sqldriver.newInstance();

    Q2:自稱Compilation failing ...是非常矛盾的。你的編譯器是否在尋找這樣的類來生成你的類?
    我相信它不是。可能是錯誤是在運行時與java.lang.ClassNotFoundException: com.mysql.jdbc.Driver。我也懷疑這個評論應該在你的聲明3下面。
    如果它是一個CNFE,您的文件路徑mysql***.jar是錯誤的。先修復它。

  3. 聲明3

    //I am using now java.sql.Driver to remove the compilation error
    //Runtime fail.. "Driver" Class not Found Exception. sqldriver = Class.forName("com.mysql.jdbc.Driver", true, sqldriver.getClassLoader()).newInstance();

    Q3:聲稱... "Driver" Class not Found Exception是suspectful。因爲,這個聲明不會被編譯。那麼它怎麼會是一個運行時失敗。 ..!?
    我也懷疑這個評論應該和你的聲明2一致。
    而在這裏,您需要先撥打newInstance(),然後在分配給sqlDriver變量之前投射到java.sql.Driver。因爲Class.forName(...只返回Class object associated with the class or interface with the given string name
    如果在上發佈聲明2已修復,則可以應用此修復程序進一步測試。

讓我希望你能得到這些聲明澄清。


我有一個工作示例代碼,下面顯示了一個經過測試的輸出。

import java.io.File; // and others as required 

public class MySQLDriveClassLoader { 
    public static void main(String [] args) throws Exception { 
    //File f = new File("/home/ravinder/soft-dump/mysql-connector-java-5.1.18-bin.jar"); 
    File f = new File("E:\\Soft_Dump\\mysql-connector-java-5.0.4\\mysql-connector-java-5.0.4-bin.jar"); 
    URLClassLoader urlCl = new URLClassLoader(new URL[] { f.toURI().toURL() }, System.class.getClassLoader()); 

    Class mySqlDriver = urlCl.loadClass("com.mysql.jdbc.Driver"); 

    //*** Start: DEBUG ************************* 
    //mySqlDriver.con // On pressing CTRL+SPACEBAR, after .con, IDE shows "No default proposals" 
    // meaning it still is not an instance of Driver, and hence can't call a method from Driver class. 

    //Incompatible conditional operand types Class and Driver 
    //System.out.println(mySqlDriver instanceof java.sql.Driver)); 

    System.out.println("mySqlDriver: " + mySqlDriver); 
    System.out.println("Is this interface? = " + mySqlDriver.isInterface()); 

    Class interfaces[] = mySqlDriver.getInterfaces(); 
    int i = 1; 
    for(Class _interface : interfaces) { 
     System.out.println("Implemented Interface Name " + (i++) + " = " + _interface.getName()); 
    } // for(...) 

    Constructor constructors[] = mySqlDriver.getConstructors(); 
    for(Constructor constructor : constructors) { 
     System.out.println("Constructor Name = " + constructor.getName()); 
     System.out.println("Is Constructor Accessible? = " + constructor.isAccessible()); 
    } // for(...) 
    //*** End : DEBUG ************************* 

    Driver sqlDriverInstance = (Driver) mySqlDriver.newInstance(); 
    System.out.println("sqlDriverInstance: " + sqlDriverInstance); 

    Connection con = null; 
    try { 
     /****************************************************************** 
     // You may fail to register the above driver 
     // hence don't depend on DriverManager to get Connected 
     //DriverManager.registerDriver(sqlDriverInstance); 
     //Driver driver = DriverManager.getDriver("com.mysql.jdbc.Driver"); // ("jdbc:mysql"); 
     Enumeration<Driver> enumDrivers = DriverManager.getDrivers(); 
     while (enumDrivers.hasMoreElements()) { 
     Driver driver = enumDrivers.nextElement(); 
     System.out.println("driver: " + driver); 
     } // while drivers 
     //******************************************************************/ 

     String dbUrl = "jdbc:mysql://:3306/test"; 
     Properties userDbCredentials = new Properties(); 
     userDbCredentials.put("user", "root"); 
     userDbCredentials.put("password", "password"); 

     // No suitable driver found for ... 
     //con = DriverManager.getConnection(dbUrl, "root", "password"); 

     // safely use driver to connect 
     con = sqlDriverInstance.connect(dbUrl, userDbCredentials); 
     System.out.println("con: " + con); 

     Statement stmt = con.createStatement(); 
     String sql = "select now()"; 
     ResultSet rs = stmt.executeQuery(sql); 
     if (rs.next()) { 
     System.out.println(rs.getString(1)); 
     } // if rs 
    } catch(Exception e) { 
     e.printStackTrace(); // only for quick debug 
    } finally { 
     try { if (con != null) con.close(); } catch (Exception ignoreThis) {} 
    } 
    } // psvm(...) 
} // class MySQLDriveClassLoader 

成功編譯和運行,導致下面的輸出:

mySqlDriver: class com.mysql.jdbc.Driver 
Is this interface? = false 
Implemented Interface Name 1 = java.sql.Driver 
Constructor Name = com.mysql.jdbc.Driver 
Is Constructor Accessible? = false 
sqlDriverInstance: [email protected] 
con: [email protected] 
2012-05-29 03:52:12.0 

+0

非常感謝您的澄清。我的懷疑很多清除..我實際上試圖獲取DriverManager類本身的實例獲取連接後,獲取Driver實例。此外,我試圖將Driver類轉換爲「com.mysql.jdbc.Driver」而不是的接口「java.sql.Driver」。它正在爲我工​​作..我做了進一步的研發到它,再次感謝信息。 – Pallavi

+0

@Pallavi這應該是被接受的答案。 –

相關問題