2012-01-03 48 views
2

我想使用jdbc4驅動程序連接到postgresql數據庫,但希望在程序運行期間設置類路徑。目的是註冊數據庫連接的驅動程序。下面的代碼解釋了我打算做的事情,但是代碼不起作用(「無法找到驅動程序!」)。爲什麼我不能這樣連接?我是否可以通過另一種方式實現相同目標?試圖通過代碼更改classpath?

String originalclasspath = System.getProperty("java.class.path"); 

    System.setProperty("java.class.path",originalclasspath + ";E:\\postgresql-9.0-802.jdbc4.jar"); 

    System.out.println(System.getProperty("java.class.path")); 

    System.out.println("Checking if Driver is registered with DriverManager."); 
    try { 
     Class.forName("org.postgresql.Driver"); 
    } catch (ClassNotFoundException cnfe) { 
     System.out.println("Couldn't find the driver!"); 
     cnfe.printStackTrace(); 
     System.exit(1); 
    } 

請回復 在此先感謝

+1

爲什麼在代碼中需要更改它?爲什麼不能在啓動應用程序時將其設置爲類路徑參數的一部分? – 2012-01-03 02:18:01

+0

可能重複的[你如何改變Java中的CLASSPATH?](http://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java) – SimonJ 2012-01-03 02:23:32

+0

即時假設用戶將足夠愚蠢的知道什麼是類路徑!! ?? – PVB 2012-01-03 02:23:35

回答