【发布时间】:2013-03-21 18:52:22
【问题描述】:
我的代码循环遍历描述需要存储在 MySQL 数据库中的信息的对象队列。我最近稍微更改了代码以关闭整个应用程序中 finally 块中的连接,以便在发生异常时不会泄漏任何内容。它很好用,除了:
有些用户有时会看到错误No operations allowed after resultset closed - 我知道错误的含义,但我不知道如何关闭它。
违规代码:
PreparedStatement s = null;
Connection conn = null;
try {
if( !queue.isEmpty() ){
conn = Prism.dbc();
if(conn == null || conn.isClosed()){
return;
}
conn.setAutoCommit(false);
s = conn.prepareStatement("INSERT query goes here");
int i = 0;
while (!queue.isEmpty()){
Handler a = queue.poll();
if( a == null || a.isCanceled() ) continue;
// .. value setting code here
s.addBatch();
if ((i + 1) % perBatch == 0) {
s.executeBatch(); // Execute every x items.
}
i++;
}
s.executeBatch();
conn.commit();
}
} catch (SQLException e) {
// error logging code
} finally {
if(s != null) try { s.close(); } catch (SQLException e) {}
if(conn != null) try { conn.close(); } catch (SQLException e) {}
}
错误指向conn.setAutoCommit(false); 行。但是,我不知道此时如何关闭连接,因为我正在明确检查其上方的已关闭/空连接。
【问题讨论】:
-
你能用sql客户端连接db并执行查询吗?
-
这发生在用户身上,我无法确定重现它的原因 - 但那些报告它的人从未遇到过这个问题,直到我将应用程序更改为使用
finally块。我很确定这不是他们的数据库的问题 - 因为重新启动我们的应用程序会重置连接。 -
我怀疑 finally 是否与它有关。这可能是 db 驱动程序问题 [因为不同用户使用的驱动程序可能不同]。我建议让用户使用 SQL 客户端连接到数据库,如果可行,请确保所有用户都安装了相同的数据库驱动程序。
-
你能提供整个堆栈跟踪吗?
-
最近遇到此问题的用户的堆栈:pastebin.com/TE5vBNkq - 链接到发生错误的源(代码如上)github.com/prism/Prism/blob/master/src/main/java/me/botsko/…