Home >Database >Mysql Tutorial >How to Handle \'Operation Not Allowed After ResultSet Closed\' Exception in Java?

How to Handle \'Operation Not Allowed After ResultSet Closed\' Exception in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 14:21:02848browse

How to Handle

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:

  • Allows you to pass back reusable objects that are independent of the connection.
  • Prevents exceptions thrown during ResultSet or statement closure from interfering with connection closure.
  • Facilitates parameterization of queries to prevent SQL injection.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn