问题描述
我们在java web项目中通过JDBC绑定数据库时,
通过以下语句可实现数据库的绑定:
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql:JFF", "postgres", "021115");
c.setAutoCommit(false); // 把自动提交给取消掉
System.out.println("Opened database successfully");
PreparedStatement pStatement = null;
String sql="SELECT * FROM member"; //直接在member表中查询
ResultSet rs = null;
try {
pStatement = c.prepareStatement(sql);//准备PreparedStatement
rs = pStatement.executeQuery();//执行查询
System.out.println(234);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
while(rs.next()){ //当该结果集的下一条数据不为空,读取下一条数据
String id = rs.getString("id"); //读取当前行名为id的列的数据
String name1 = rs.getString("name");
System.out.println("id:"+id+" 姓名:"+name1);
}
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
需要使用
Class.forName("org.postgresql.Driver");
来绑定Postgresql的Driver
可能会出现如下报错:
java.lang.ClassNotFoundException: org.postgresql.Driver WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.catalina.loader.WebappClassLoaderBase (file:/D:/tool/apache-tomcat-9.0.39/lib/catalina.jar) to field java.io.ObjectStreamClass$Caches.localDescs WARNING: Please consider reporting this to the maintainers of org.apache.catalina.loader.WebappClassLoaderBase WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release
原因如下:
-
eclipse 构建路径中没有postgres的jar包
PostgreSQL JDBC Download
下载对应版本jar 包,在eclipse中右键项目-构建路径-配置构建路径

添加外部JAR-选择刚刚下载的jar包-应用并关闭

-
在进行了上述操作后,仍然会报错
将JAR包放入src/main/webapp/WEB-INF/lib

即可解决问题。










