关闭连接后没有操作,绕过我的关闭连接检查?

时间:2013-03-31 15:16:07

标签: java mysql jdbc

我的代码循环遍历描述需要存储在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);行。但是,我没有看到此时如何关闭连接,因为我明确地检查了它上面的闭合/空连接。

2 个答案:

答案 0 :(得分:0)

我在堆栈跟踪中发现的核心问题是: 2013-03-31 13:21:11 [SEVERE] Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 30,491,788 milliseconds ago. The last packet sent successfully to the server was 30,491,788 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

调用Prism.dbc();时获得的连接实际上是来自连接池的连接;在这种特定情况下,池化连接已损坏。它表示池中的JDBC连接与数据库之间的通信时间超过8h。也许是因为在数据库服务器上定义的wait_timeout或者防火墙丢弃了连接或任何东西;连接断开的原因可能有很多。

您应该遵循异常提出的建议来解决此问题。

答案 1 :(得分:-1)

此问题的最可能原因是JDK版本与正在使用的DB驱动程序之间不兼容。

检查此链接:http://dev.mysql.com/downloads/connector/j,它提供各种版本的数据库驱动程序。

编辑:

查看jdk和驱动程序映射的此链接:http://dev.mysql.com/doc/refman/5.1/en/connector-j-versions-java.html

编辑:

我说这是最可能的原因是因为使用DB的经验。我不认为这是一个代码问题,因为它适用于某些人。使用不兼容的驱动程序可能会导致您遇到的奇怪问题。 我遇到过Oracle DB的问题,我可以执行除Merge查询之外的所有查询,导致关闭连接,问题是由于驱动程序不兼容。

所以我根据自己的经验这说。

此外我觉得即使这不是问题的确切原因[它最有可能导致问题]如果用户可以发布驱动程序版本和jdk版本我们可以肯定地排除这个,这个帖子当然可以帮助人们,所以我没有看到downvote的原因。