【发布时间】:2017-02-16 21:03:41
【问题描述】:
我正在尝试通过 jdbc 访问 PostgreSQL。下面的代码不是从 Eclipse 运行的,而是从命令行运行的。有什么建议我可以从 Eclipse 中运行它吗? postgresql-9.4.1211.jar 在 CLASSPATH 中,它与下面的包完全不同。
Windows 7、java 1.8.0.101.b13、postgres 9.5.3、Eclipse 4.5.1
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了吗?
标签: java eclipse postgresql jdbc