不允许操作:Java 中的 ResultSet 关闭异常
在执行某些 SQL 查询时,开发人员可能会遇到“java.sql.SQLException:结果集关闭后不允许操作”异常。当从同一个 Statement 对象同时尝试多个 ResultSet 时,通常会发生此错误。
请考虑演示此问题的以下代码片段:
// Problem code: using the same statement object to create multiple ResultSets try { // Execute the first query and obtain ResultSet rs ResultSet rs = statement.executeQuery("SELECT `name` FROM `user` WHERE `id` = " + userId + " LIMIT 1;"); // Execute the second query and obtain ResultSet rs2 ResultSet rs2 = statement.executeQuery("SELECT `id` FROM `profiles` WHERE `id` =" + profId + ";"); // Prepare a new statement and attempt to use rs2 PreparedStatement pst = (PreparedStatement)connection.prepareStatement("INSERT INTO `blah`............"); // Process data from rs2 and update the database using pst while(rs2.next()) { int id = rs2.getInt("id"); int stuff = getStuff(id); pst.setInt(1, stuff); pst.addBatch(); } pst.executeBatch(); } catch (Exception e) { e.printStackTrace(); }
在此代码中,两个 ResultSet(rs 和 rs ) rs2) 是从同一个 Statement 对象(语句)创建的。然而,虽然 rs 没有显式关闭,但当执行第二个查询并获取 rs2 时,它会隐式关闭。这会导致异常,因为 rs2 正在尝试对关闭的 ResultSet 进行操作。
解决方案:
要解决此问题,在使用之前关闭所有 ResultSet 至关重要相同的Statement对象来获取新的ResultSets。这可以通过使用 try-finally 块来确保即使发生异常也关闭 ResultSet:
// Corrected code: closing the ResultSet objects try { // Execute the first query and obtain ResultSet rs ResultSet rs = statement.executeQuery("SELECT `name` FROM `user` WHERE `id` = " + userId + " LIMIT 1;"); // Use rs to retrieve data if(rs.next()) { String name = rs.getString("name"); } // Close rs rs.close(); // Execute the second query and obtain ResultSet rs2 ResultSet rs2 = statement.executeQuery("SELECT `id` FROM `profiles` WHERE `id` =" + profId + ";"); // Use rs2 to retrieve data while(rs2.next()) { int id = rs2.getInt("id"); int stuff = getStuff(id); pst.setInt(1, stuff); pst.addBatch(); } // Close rs2 rs2.close(); pst.executeBatch(); } catch (Exception e) { e.printStackTrace(); }
以上是如何解决 Java 中的'java.sql.SQLException:结果集关闭后不允许操作”异常?的详细内容。更多信息请关注PHP中文网其他相关文章!