【问题标题】:Return ResultSet in try with resources java.sql.SQLException: Operation not allowed after ResultSet closed使用资源 java.sql.SQLException 返回 ResultSet:ResultSet 关闭后不允许操作
【发布时间】:2020-10-12 19:40:01
【问题描述】:

我有一个名为 CustomerController 的文件,它将从 MyConnectToMySQL 获取 ResultSet 返回,然后添加到 ArrayList 中

我正在切换到 Try-with-Resources 因为我想确保它已关闭并且我不想每次运行某些东西时都靠近(顺便说一句,有时它会出现错误并且没有关闭会使我的应用程序变慢) .

旧的工作得很好。但是当我切换到 Try-with-resources 时出现错误开始

java.sql.SQLException: Operation not allowed after ResultSet closed

AFAIK,这是因为 Try-with-resources 在完成连接后关闭了连接,因此当我返回 ResultSet 时它无法访问。 所以我现在的解决方案是在我的 CustomerController 中建立一个连接,当我得到 resultSet 时,我在关闭之前将它添加到 ArrayList。

对这个问题有什么想法吗?我不想将它合并到 CustomerController(我认为会起作用),因为我想在将来与其他 Controller 重用它。

    public class CustomerController {
        MyConnectToMySQL conn = null;
        ResultSet rs = null;
        ArrayList<nguoidungDTO> dsnd = null;
    
        public CustomerController () {
            if (conn == null) {
                conn = new MyConnectUnit("localhost", "root", "", "thuvien");
            }
        }
    
        public ArrayList<nguoidungDTO> docDSND() throws Exception {
            dsnd = new ArrayList<nguoidungDTO>();
            rs = conn.excuteQuery("SELECT * FROM nguoidung");
            while (rs.next()) {
                nguoidungDTO nguoidung = new nguoidungDTO();
                nguoidung.setManv(rs.getString(1));
                nguoidung.setMkhau(rs.getString(2));
                nguoidung.setQuyen(rs.getString(3));
                dsnd.add(nguoidung);
            }
//Old, each time I have done used, I will close by hand
            //conn.Close();
            return dsnd;
        }
    }

MyConnectToMySQL

    package DAO;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class MyConnectToMySQL {
    
        String Host = "";
        String UserName = "";
        String Password = "";
        String Database = "";
    
        Connection connect = null;
        Statement statement = null;
        ResultSet rs = null;
    
        public MyConnectToMySQL(String Host, String UserName, String Password, String Database) {
            this.Host = Host;
            this.UserName = UserName;
            this.Password = Password;
            this.Database = Database;
        }
    
        public void DriverTest() throws Exception {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                throw new Exception("MySQL Driver JDBC not found");
            }
        }
    //old
        protected Connection getConnection() throws Exception {
            if (this.connect == null) {
                DriverTest();
                String url = "jdbc:mysql://" + this.Host + ":3306/" + this.Database
                        + "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8";
                try {
                    this.connect = DriverManager.getConnection(url, this.UserName, this.Password);
                } catch (SQLException e) {
                    throw new Exception("Can't coonect MySQL server " + e);
                }
            }
            return this.connect;
        }
    //old
        protected Statement getStatement() throws Exception {
            
            if (this.statement == null ? true : this.statement.isClosed()) {
                
                this.statement = this.getConnection().createStatement();
            }
            return this.statement;
        }
    
    //Old
        /*public ResultSet excuteQuery(String query) throws Exception {
            try {
                this.rs = getStatement().executeQuery(query);
            } catch (Exception e) {
                throw new Exception("Error : " + e.getMessage());
            }
            
            return this.rs;
        }*/
        
    //Switching to Try-With-Resources
        public ResultSet excuteQuery(String query) throws Exception  {
            DriverTest();
            String url = "jdbc:mysql://" + this.Host + ":3306/" + this.Database
                    + "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8";
            ResultSet myResult = null;
            try(Connection con = DriverManager.getConnection(url, this.UserName, this.Password);
                     Statement statement = con.createStatement();
                    ) {
                try (ResultSet res = statement.executeQuery(query)) {
                    myResult = res;
                    
                    System.out.println(myResult);
                    return myResult;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
    //Must return here too
    return myResult;
            }
        
            public void Close() throws Exception {
                if (this.rs != null && !this.rs.isClosed()) {
                    this.rs.close();
           }
            if (this.statement != null && !this.statement.isClosed()) {
                this.statement.closed();
            }
            if (this.connect != null && !this.connect.isClosed()) {
                this.connect.closed();
            }
        }
    }

【问题讨论】:

  • KorbirT - 有更新吗?
  • 仍在寻找更多答案。
  • 您的方法不应尝试返回ResultSet。这已经是一次尝试的泄漏,但由于异常中所述的原因而失败。 ResultSet 和 Statement 甚至 Connection 都不应该是实例变量。它们都应该是局部变量。否则(a)您的类不是线程安全的,(b)您可能会遇到关闭的连接,因为它们是长期打开的,并且(c)您会遇到这样的问题。因此,您也不应该拥有getConnection(), getStatement() 或Close()。你需要从根本上重新考虑这一切。

标签: java mysql swing jdbc resultset


【解决方案1】:

当您使用try-with-resources 时,资源会在try 块完成后关闭。之后,如果您尝试显式关闭它,您将收到错误消息。你正在做:

this.rs.close();

如果调用此语句将导致问题。这是因为您使用try-with-resources 创建了Connection、Statement 和Resultset。

确保方法 public void Close() 未被调用,或者最好从该方法中删除上述语句,以避免在出于其他目的使用/调用此方法时意外调用它。

我还可以在您的代码中看到以下几行:

this.statement.closed();
this.connect.closed();

这将导致编译失败,因为 java.sql.Connection 和 java.sql.Statement 都没有 closed() 方法。可能您想输入close()。但是,请确保出于与上述相同的原因删除这些语句。

【讨论】:

  • 我的第一个版本是使用带有 Captical C 的 conn.Close() 手动关闭(抱歉命名错误),在每个 CustomerController 方法的末尾调用。当我切换到 Try-with-resources 时,我已经评论了该行,因此不应再执行此方法。我将删除该方法并在我回家后重试
猜你喜欢
  • 2014-05-02
  • 2014-11-11
  • 1970-01-01
  • 2012-06-11
  • 2011-12-01
  • 2017-04-17
  • 2018-03-20
相关资源
最近更新 更多