【问题标题】:Operation not allowed after ResultSet closed during while loop在while循环期间ResultSet关闭后不允许操作
【发布时间】:2020-10-26 09:13:46
【问题描述】:

我在 while 循环期间遇到了结果集问题。它给了我一个错误 java.sql.SQLException: Operation not allowed after ResultSet closed 我想不通。谁能帮我吗?谢谢!

public static void CandidatesPartyList_JComboBox() {
    try {
        conn1 = VotingSystem.con();
        ps = conn1.prepareStatement("SELECT * FROM partylist WHERE p_status = 'Active' ORDER BY p_name ASC");
        rs = ps.executeQuery();
        candidates_filter_partylist.removeAllItems();
        candidates_filter_partylist.addItem("- Select PartyList -");
        while (rs.next()) { **<< The problem is coming from here**
            candidates_filter_partylist.addItem(rs.getString("p_name"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn1 != null) {
            try {
                conn1.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

【问题讨论】:

    标签: java netbeans


    【解决方案1】:

    您有名为conn1psrs 的静态变量。静态意味着整个虚拟机只有一个变量

    很明显,CandidatesPartyList_JComboBox 被不同的线程调用了两次,因此变量被覆盖了。

    解决方案是:这些东西都不应该是字段。它们应该是局部变量,并且您应该使用 try-with-resources,这使得该代码的大小小于一半并解决了问题。让我们也修复糟糕的错误处理(“打印堆栈跟踪”没有处理事情,所以永远不要写它并更新你的 IDE 模板)。

    public static void CandidatesPartyList_JComboBox() {
        try (Connection c = VotingSystem.con();
             PreparedStatement ps = c.prepareStatement("SELECT * FROM partylist WHERE p_status = 'Active' ORDER BY p_name ASC");
             ResultSet rs = ps.executeQuery()) {
    
            candidates_filter_partylist.removeAllItems();
            candidates_filter_partylist.addItem("- Select PartyList -");
            while (rs.next()) {
                candidates_filter_partylist.addItem(rs.getString("p_name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException("Unhandled", e);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-11
      • 2017-04-17
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      相关资源
      最近更新 更多