【发布时间】:2014-06-27 00:55:16
【问题描述】:
我正在使用 Oracle 数据库,一段时间后我收到以下异常:
java.sql.SQLException: ORA-01000: maximum open cursors exceeded
我分析了我的代码,我似乎要关闭所有 ResultSet。此异常仅偶尔发生。由于这个错误,我决定稍微改变我的代码。下面是代码:
public class Audit {
private Connection connection;
private PreparedStatement insertAuditPreparedStatementSent;
private static int counter;
private static int JDBC_COUNTER;
public Audit() throws Exception {
connection = DriverManager.getConnection("url", "username", "password");
}
public int insertAudit(String message, java.util.Date sent) throws Exception {
PreparedStatment preparedStatement = prepareStatement(new String("INSERT INTO Audit (message, sent) VALUES (?, ?)");
if(JDBC_COUNTER == 0) {
// this is required to be executed so that ORA-08002 SQLException is not thrown
connection.createStatement().executeQuery(new String("SELECT AUDIT_SEQUENCE.NEXTVAL FROM DUAL"));
}
ResultSet resultSet = connection.createStatement().executeQuery(new String("SELECT AUDIT_SEQUENCE.CURRVAL FROM DUAL"));
resultSet.next();
primaryKey = resultSet.getInt(new String("CURRVAL"));
resultSet.close();
return primaryKey;
}
public void executeUpdateAudit(int id, java.util.Date sent) throws Exception {
if(updateAuditPreparedStatement == null) {
updateAuditPreparedStatement = connection.prepareStatement(new String("UPDATE AUDIT SET SENT = ? WHERE AUDIT_ID = " + id));
}
updateAuditPreparedStatement.setTimestamp(1, new java.sql.Timestamp(sent.getDate());
int i = updateAuditPreparedStatement.executeUpdate();
connection.commit();
}
public static void main(String[] args) throws Exception {
Audit audit = new Audit();
int primaryKey = audit.insertAudit("message", new java.util.Date());
audit.executeUpdateAudit(primaryKey, new java.util.Date());
int primaryKey2 = audit.insertAudit("message2", new java.util.Date());
audit.executeUpdateAudit(primaryKey2, new java.util.Date());
}
}
在插入记录 2 和更新记录 2 时,只有 updateAuditPreparedStatement.executeUpdate() 返回 1,但数据库更新第一条记录而不是第二条记录。
更改代码的原因是因为我相信 PreparedStatement 每次都会创建一个新游标。所以,我希望 insertAuditPreparedStatementSent 出现在许多插入上而不关闭。我试过insertAuditPreparedStatementSent.clearBatch() 和insertAuditPreparedStatementSent.clearParameters()。
我不确定它为什么要更新记录 2 的主键上的记录 1。SQL 很好。
有什么想法吗?
【问题讨论】:
标签: java oracle jdbc prepared-statement