mlodikkal mlodikkal - 10 months ago 72
SQL Question

Java - Can't use ResultSet after connection close

I have a problem with closing a connection to MySQL.

I'm getting the error:

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

My code:

public static ResultSet sqlquery (String query)
ResultSet rs=null;
Connection connection=null;
Statement st=null;
connection = DriverManager.getConnection("databaseadress","username","password");
st = connection.createStatement();
rs = st.executeQuery(query);

}catch(SQLException e){System.out.println("SQL error: " + e);}
catch(Exception e){System.out.println("Error: " + e);}
finally {
if(rs != null) rs.close();
if(st!= null) st.close();
if(connection != null) connection.close();
}catch(SQLException e){System.out.println("SQL error : " + e);}

return rs;


This is the way JDBC works. In your code you closed the ResultSet and the Connection, after which the ResultSet is no longer usable. If you want it to be usable you must leave it (and the Connection) open.

However, if you return the ResultSet, you should refactor your code so the calling method provides the Connection.