許多 Java 開發者在使用 Oracle 時遭遇 ORA-01000: maximum open cursors exceeded。錯誤本質是程式碼未正確關閉游標,而非參數不足。單純調大 open_cursors 只能治標不治本。
conn.createStatement()、conn.prepareStatement() 在資料庫端會開啟一個游標。Statement/ResultSet,游標也會洩漏。// 1. Statement/PreparedStatement 放在迴圈外部
PreparedStatement pstmt = conn.prepareStatement("SELECT ... WHERE id = ?");
try {
for (int id : ids) {
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
try {
while (rs.next()) { /* 處理資料 */ }
} finally {
rs.close(); // 立即關閉 ResultSet
}
}
} finally {
pstmt.close(); // 最後關閉 Statement
}
executeQuery/Update,若不再需要 ResultSet,立即 close()。try-with-resources (Java 7+) 或 finally 區塊確保資源釋放。maxOpenPreparedStatements 避免洩漏擴散。V$SESSTAT / V$SYSSTAT 中 opened cursors current 觀察實際用量。徹底解決 ORA-01000 的唯一出路是修正程式碼資源管理,而非調大參數掩蓋問題。