Search code examples
javamysqlresultset

Operation not allowed after ResultSet closed, mysql


Whenever I try and run this code I get: "java.sql.SQLException: Operation not allowed after ResultSet closed". It works without closing the connection but i'm curious as to why I get this error and what would be the correct way to close the connection, Here is the code:

    public ResultSet UpdateTable(){

            Connection con = connect();
            ResultSet resultset;
            Statement s = null;
            resultset = null;
        try{
            s = con.createStatement();
            resultset =  s.executeQuery("select * from customera");
            return resultset;

            }
        catch(SQLException e){
            System.out.println(e.getMessage());
            //con.close();
        }
        finally{
            try{
                s.close();
                resultset.close();
                con.close();
            }
            catch(SQLException e){
                System.out.println(e.getMessage());
            }
        }
        return null;
    }

}

Solution

  • You would rather check whether they have any reference or not, then close them.

     finally {
    
            if (resultset != null) {
                resultset.close();
            }
    
            if (s != null) {
                s.close();
            }
    
            if (con != null) {
                con.close();
            }
    
        }
    

    I suspect, issue with

    return resultset;
    

    Since, you are closing the Connection and Statement before returning the ResultSet, so ResultSet might not be available. You must be aware finally block will execute before returning the value. That is also why, your code is working when you left your Connection open.

    So, instead you should store the result into some data structure and return.