【问题标题】:SQL Exception: Operation not allowed after ResultSet closed. Why is that?SQL 异常:ResultSet 关闭后不允许操作。这是为什么?
【发布时间】:2019-11-20 21:00:54
【问题描述】:

我尝试从数据库中获取一条数据,突然报错: ResultSet 关闭后不允许操作。在

的行上
while(rs3.next()) {

为什么会这样?代码似乎没问题,一切都好。这是我的代码:

public DatabaseConnectionClass() {

    idfield = new JTextField("");
    submit = new JButton("go");
    settings = new JButton("settings");
    auto = new JButton("auto");
    add(idfield);
    add(submit);
    add(settings);
    add(auto);
    setLayout(new GridLayout());

    try {

        Class.forName("com.mysql.cj.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database1?useTimezone=true&serverTimezone=UTC", "root", "");
        st = con.createStatement();
        con2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/values?useTimezone=true&serverTimezone=UTC", "root", "");
        st2 = con2.createStatement();


    } catch(Exception ex) {
        System.out.println(ex);



    }
    }

这是在按下其中一个按钮时激活的错误方法(称为自动):

 public void getAuto() throws Exception {

            for (int i = 0; i < 1000; i++) {

            String q1 = "SELECT * FROM payments LIMIT 1";
            try {
                rs3=st.executeQuery(q1);
                while(rs3.next()) {
                String ppmail = rs3.getString("mail");
                getData(ppmail);
                rs3.close();

                }} catch (SQLException e) {

                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println(e);
                auto.setText("End of records");
            }


            }


}

【问题讨论】:

  • 您正在关闭循环中的结果集,并在其中进行迭代。考虑在 循环之后关闭它。
  • 它仍然给我一个

标签: java mysql sql resultset sqlexception


【解决方案1】:

ResultSet 之后不能使用ResultSet,将rs3.close(); 移动到finally

            }} catch (SQLException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e);
            auto.setText("End of records");
        } finally { 
             if (s3 != null){
                 s3.close();
             }
        }

立即释放此 ResultSet 对象的数据库和 JDBC 资源

【讨论】:

  • 将其转换为 try-with-resources 很可能是一个更好的选择。
  • @NiceGuy “它仍然给我一个错误”不是有用的信息。 它会给您带来什么错误?
  • @Amongalen rs3 不是方法中的局部变量
  • @user7294900 没错,但这会让事情变得更糟。我想不出任何理由让 ResultSet 保持全球性。
  • @JonK 同样的错误:ResultSet 关闭后不允许操作
猜你喜欢
  • 2021-01-25
  • 2012-03-06
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 2017-04-17
  • 2018-03-20
相关资源
最近更新 更多