找不到加载 JDBC org.postgresql.Driver 的类
我正在开发一个Web项目,我最近安装了postgres 9.1.1
postgresql 服务器已启动并正在运行。我可以像往常一样通过psql连接,并且所有内容都已从我从8.5创建的数据库的转储中加载并正确保存。
所以我也在这里下载了9.1 postgres版本的JDBC4驱动程序:http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz
我通过 eclipse 使用项目属性将其添加到 java 构建路径中。
这是我用来向其他类提供数据库连接的代码(即,它是一个单例,只有当现有连接关闭或为空时,我才会获得新连接,一次只能从一个对象获得)
public abstract class DBConnection {
private static Connection connection = null;
public static void connect() {
try {
if (connection == null) {
String host = "127.0.0.1";
String database = "xxxxx";
String username = "xxxxx";
String password = "xxxxx";
String url = "jdbc:postgresql://" + host + "/" + database;
String driverJDBC = "org.postgresql.Driver";
Class.forName(driverJDBC);
connection = DriverManager.getConnection(url, username,
password); //line firing the class not found exception
} else if (connection.isClosed()) {
connection = null;
connect();
}
} catch (SQLException e) {
e.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
public static Connection getConnection() {
try {
if (connection != null && !connection.isClosed()) {
return connection;
} else {
connect();
return connection;
}
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE,
null, e);
return null;
}
}
@Override
public void finalize() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
}
正如我在运行项目时在标题中所写的那样,一个类要求连接到这个类,我总是得到一个类未找到异常,因为它显然无法加载org.postgresql.Driver.class驱动程序位于项目的子文件夹中~/lib/org.postgresql-9.1-901.jdbc4.jar正如我所说,通过eclipse项目属性添加到构建路径中。
我还提供了一个示例查询,让我们查看我的类访问 DBConnection 的通常行为:
public static final User validateUserCredentials(String id, String pswd) {
Connection connection = DBConnection.getConnection();
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, (connection!=null)?"connection not null":"connection null");
Statement stmt = null;
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, "validating credentials for user: username : " + id + " password : " + pswd);
String sql = "Select * from fuser where id = '" + id + "'";
ResultSet resultset = null;
try {
stmt = connection.createStatement();
resultset = stmt.executeQuery(sql);
Logger.getLogger(Credentials.class.getName())
.log(Level.SEVERE, sql);
resultset.next();
String password = resultset.getString("pswd");
if (pswd.equals(password))
return new User(id, pswd);
} catch (SQLException ex) {
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
if (stmt != null)
stmt = null;
if (resultset != null)
resultset = null;
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
connection = null;
}
}
return null;
}