2016-10-07 81 views
1

我試圖通過jdbc訪問PostgreSQL。下面的代碼不能從Eclipse運行,但它從命令行運行。任何建議如何從Eclipse中運行它? postgresql-9.4.1211.jar位於CLASSPATH中,與下面的包完全不同。 的Windows 7,JAVA 1.8.0.101.b13,Postgres的9.5.3,4.5.1的Eclipse在Eclipse中找不到JDBC驅動程序,但在獨立運行時發現

package PostTest; 

import java.sql.*; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class Version 
{ 

    public static void main(String[] args) 
    { 

     Connection con = null; 
     Statement st = null; 
     ResultSet rs = null; 


     String url = "jdbc:postgresql://localhost/nederland"; 
     String user = "postgres"; 
     String password = "Hallo Postgres!"; 

     System.out.println ("Testing for driver"); 

     try 
     { 
     Class.forName("org.postgresql.Driver"); 
     // Success. 
     System.out.println ("driver found"); 
     } catch (ClassNotFoundException e) 
     { 
     // Fail. 
     System.out.println ("driver lost"); 
     } 

     System.out.println ("Trying to connect"); 
     try 
     { 
     con = DriverManager.getConnection(url, user, password); 
     st = con.createStatement(); 
     rs = st.executeQuery("SELECT VERSION()"); 

     if (rs.next()) { 
      System.out.println(rs.getString(1)); 
     } 

     } catch (SQLException ex) 
     { 
     Logger lgr = Logger.getLogger(Version.class.getName()); 
     lgr.log(Level.SEVERE, ex.getMessage(), ex); 

     } finally 
     { 
     try 
     { 
      if (rs != null) 
      { 
       rs.close(); 
      } 
      if (st != null) 
      { 
       st.close(); 
      } 
      if (con != null) 
      { 
       con.close(); 
      } 

     } catch (SQLException ex) 
     { 
      Logger lgr = Logger.getLogger(Version.class.getName()); 
      lgr.log(Level.WARNING, ex.getMessage(), ex); 
     } 
     } 
    } 
} 

當從Eclipse中運行我得到:

Testing for driver 
driver lost 
Trying to connect 
Oct 07, 2016 8:43:02 PM PostTest.Version main 
SEVERE: No suitable driver found for jdbc:postgresql://localhost/nederland 
java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost/nederland 
    at java.sql.DriverManager.getConnection(Unknown Source) 
    at java.sql.DriverManager.getConnection(Unknown Source) 
    at PostTest.Version.main(Version.java:38) 

當在命令行中運行:

D:\home\arnold\development\java\projects\PostTest\bin>java PostTest.Version 
Testing for driver 
driver found 
Trying to connect 
PostgreSQL 9.5.3, compiled by Visual C++ build 1800, 64-bit 
+0

你檢查了你的'BuildPath'嗎? – brso05

回答

1

如果PostgreSQL庫是在您的項目(例如,/ lib文件夾),右擊它 - >構建路徑 - >添加到構建路徑

如果庫是不是在你的項目中,右鍵點擊你的項目 - >構建路徑 - >配置構建路徑...然後在庫選項卡中單擊並添加外部JAR ...然後選擇postgresql-9.4.1211.jar文件並單擊確定。

+0

當然,非常感謝您的支持! – Arnold

相關問題