Java数据库连接关闭后无法启动

时间:2022-05-10 15:34:42

错误如下:

java.sql.SQLException: No operations allowed after connection closed.

at com.mysql.jdbc.Connection.checkClosed(Connection.java:1842)
at com.mysql.jdbc.Connection.prepareStatement(Connection.java:4260)
at com.mysql.jdbc.Connection.prepareStatement(Connection.java:4226)
at hist.nws.db.SqlHelper.query(SqlHelper.java:140)
at hist.nws.service.OperationService.queryActivity(OperationService.java:60)
at MainFrame.<init>(MainFrame.java:115)
at MainFrame.main(MainFrame.java:331)

错误原因:

private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;

数据库的连接Connection为Static的,程序共享这一个Connection。所以第一次对数据库操作没问题,当把Connection关闭后,第二次还想操作数据库时Connection肯定不存在了。