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:
x
public static ResultSet sqlquery (String query)
{
ResultSet rs=null;
Connection connection=null;
Statement st=null;
try{
Class.forName("com.mysql.jdbc.Driver");
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 {
try{
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;
}
Advertisement
Answer
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
.