Home >Database >Mysql Tutorial >How to Handle \'Operation Not Allowed After ResultSet Closed\' Exception in Java?
Java - Handling "Operation Not Allowed After ResultSet Closed" Exception
When closing a MySQL connection, you may encounter the error "Operation not allowed after ResultSet closed." This occurs because JDBC retrieves query results gradually, providing you with a ResultSet that will become invalid when the connection closes.
Cause of the Exception
The ResultSet you return from your method relies on the open connection. When you close the connection within the finally block, the ResultSet becomes unusable, leading to the exception.
Solution
Instead of returning the ResultSet, create a method that uses it to populate an object or collection of objects. Then, return the populated object or collection.
Refactored Code
The following code shows a modified version of your method:
<code class="java">public static List<T> sqlquery(String query, RowMapper<T> rowMapper) throws SQLException { Connection connection = DriverManager.getConnection("databaseadress", "username", "password"); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(query); List<T> list = new ArrayList<>(); while (rs.next()) { list.add(rowMapper.mapRow(rs)); } try { rs.close(); st.close(); connection.close(); } catch (SQLException e) { log.info(e); } return list; }</code>
Using RowMapper
The RowMapper interface is used to map each row of the ResultSet to an object. You can create your own implementation of RowMapper based on the object you want to populate.
Benefits
This approach:
Conclusion
To avoid "Operation not allowed after ResultSet closed" exceptions, modify your code to populate objects or collections using a RowMapper and return those instead of the ResultSet. This approach ensures that your methods remain functional after connection closure.
The above is the detailed content of How to Handle \'Operation Not Allowed After ResultSet Closed\' Exception in Java?. For more information, please follow other related articles on the PHP Chinese website!