Problem:
An exception, "java.sql.SQLException: Operation not allowed after ResultSet closed," arises when closing a connection to a MySQL database, indicating an issue with ResultSet handling after connection termination.
Code Excerpt:
<code class="java">public static ResultSet sqlquery(String query) { ResultSet rs = null; Connection connection = null; Statement st = null; try { // Establish connection and execute query } finally { // Attempt to close connection and ResultSet objects } return rs; }</code>
Explanation:
JDBC does not retrieve all query results to the ResultSet immediately. Instead, it provides an object that facilitates result retrieval. However, this object becomes invalid upon connection closure.
Solution:
To avoid this issue, the code should create an object to store the query results before closing the connection. This involves using a RowMapper to map ResultSet rows to objects and populate a collection that is returned as the method's result.
Resolved Code:
<code class="java">public static <T> List<T> sqlquery(String query, RowMapper<T> rowMapper) { Connection connection = null; Statement st = null; ResultSet rs = null; try { // Establish connection and execute query } finally { // Handle possible exceptions gracefully } while (rs.next()) { list.add(rowMapper.mapRow(rs)); } return list; }</code>
Additional Notes:
The above is the detailed content of Why am I getting \"java.sql.SQLException: Operation not allowed after ResultSet closed\" when closing my MySQL Connection in Java?. For more information, please follow other related articles on the PHP Chinese website!