不允許操作: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中文網其他相關文章!