我试图通过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
答案 0 :(得分:1)
如果PostgreSQL库在您的项目中(例如/ lib文件夹),请右键单击它 - >构建路径 - > 添加到构建路径。
如果您的项目中没有库,请右键单击您的项目 - >构建路径 - > 配置构建路径... 然后单击Libraries选项卡并添加外部JAR ... 然后选择postgresql-9.4.1211.jar文件并单击OK。