我試圖通過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
你檢查了你的'BuildPath'嗎? – brso05