出现下面的报错:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.result.ResultSetImpl.checkClosed(ResultSetImpl.java:445)
at com.mysql.cj.jdbc.result.ResultSetImpl.next(ResultSetImpl.java:1726)
部分原代码如下:
private void execute(){
try(Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/BMS?serverTimezone=GMT%2B8","3219003920","lxhd")) {
Statement statement = con.createStatement();
statement.execute("begin;");
String sql="select id from Reader where id=" + this.reader.getid();
ResultSet ls =statement.executeQuery(sql);
while (ls.next()){
statement.executeUpdate("delete from Reader where id=" + this.reader.getid());
complete = true;
}
statement.execute("commit;");
} catch(Exception e1) {
e1.printStackTrace();
}
}
通过网上查找资料发现主要因为每执行一次execue操作ls就会被自动地关闭。而对一个已经关闭的ls再执行next显然是错误的。因此在while语句里面添加,这样在每次用到statement的时候都创建一个新的Statement对象。这样就不会重复的使用ls了。
statement = con.createStatement();
修改代码如下:
private void execute(){
try(Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/BMS?serverTimezone=GMT%2B8","3219003920","lxhd")) {
Statement statement = con.createStatement();
statement.execute("begin;");
String sql="select id from Reader where id=" + this.reader.getid();
ResultSet ls =statement.executeQuery(sql);
while (ls.next()){
statement = con.createStatement();
statement.executeUpdate("delete from Reader where id=" + this.reader.getid());
complete = true;
}
statement.execute("commit;");
} catch(Exception e1) {
e1.printStackTrace();
}
}