Java 在Eclipse中找不到JDBC驱动程序,但在独立运行时找到
我正在尝试通过jdbc访问PostgreSQL。下面的代码不是从Eclipse运行的,而是从命令行运行的。有没有关于如何从Eclipse运行它的建议?Java 在Eclipse中找不到JDBC驱动程序,但在独立运行时找到,java,eclipse,postgresql,jdbc,Java,Eclipse,Postgresql,Jdbc,我正在尝试通过jdbc访问PostgreSQL。下面的代码不是从Eclipse运行的,而是从命令行运行的。有没有关于如何从Eclipse运行它的建议?postgresql-9.4.1211.jar位于类路径中,与下面的包位于完全不同的位置。 Windows7、Java1.8.0.101.b13、Postgres9.5.3、Eclipse4.5.1 package PostTest; import java.sql.*; import java.util.logging.Level; impor
postgresql-9.4.1211.jar
位于类路径中,与下面的包位于完全不同的位置。
Windows7、Java1.8.0.101.b13、Postgres9.5.3、Eclipse4.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
如果PostgreSQL库在您的项目中(例如/lib文件夹),请右键单击它->构建路径->添加到构建路径
如果库不在您的项目中,请右键单击项目->构建路径->配置构建路径…然后单击库选项卡并添加外部jar…,然后选择postgresql-9.4.1211.jar文件并单击确定。是否检查了
构建路径?