while 循环期间 ResultSet 关闭后不允许操作

Operation not allowed after ResultSet closed during while loop

我在 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();
            }
        }
    }
}

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

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

解决方法是:None那些东西应该是字段。它们应该是局部变量,并且您应该使用 try-with-resources,这使得这段代码的大小减少了一半并解决了问题。让我们也修复糟糕的错误处理('print the stack trace' 没有处理事情,所以永远不要写那个并更新你的 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);
    }
}