我正在为MySQL使用tomcat jdbc池库。很少,用户会报告看到以下错误:
Operation not allowed after ResultSet closed
错误指向下面的while(rs.next())
代码,但我无法理解它是如何被关闭的。我关闭结果集,语句或连接的唯一位置在finally
块中,这使我相信如果出现某种错误,jdbc中的某些内容会自动关闭结果集/语句。
我在我们的应用程序中看到了类似的问题 - 在while循环的中间关闭了一个连接或语句,就像批量插入或其他东西一样。
但是,我找不到关于此的文档。这是我们的代码,删除了不相关的部分但解释了:
Connection conn = null;
PreparedStatement s = null;
ResultSet rs = null;
try {
conn = getConnection();
if( conn == null || conn.isClosed() ){
// ... we do stuff here
}
s = conn.prepareStatement(query);
rs = s.executeQuery();
while(rs.next()){ // sometimes, we see "resultset closed" errors here, but we never close them
try {
// we read the data, construct an object with, i.e. rs.getString(3)
// some is json we parse, so we catch exceptions
} catch (Exception e) {
if( !rs.isClosed() ){
// print the primary key to help find the invalid record
}
e.printStackTrace();
}
}
} catch (SQLException e) {
handleDatabaseException( e );
} finally {
if(rs != null) try { rs.close(); } catch (SQLException ignored) {}
if(s != null) try { s.close(); } catch (SQLException ignored) {}
if(conn != null) try { conn.close(); } catch (SQLException ignored) {}
}