gpt4 book ai didi

java - PreparedStatementexecuteUpdate()更新错误记录

转载 作者:行者123 更新时间:2023-12-01 13:00:20 24 4
gpt4 key购买 nike

我正在使用 Oracle 数据库,一段时间后我收到以下异常:

java.sql.SQLException: ORA-01000: maximum open cursors exceeded

我分析了我的代码,我似乎正在关闭所有结果集。这种异常只是有时发生。由于这个错误,我决定稍微更改一下我的代码。下面是代码:

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 没问题。

有什么想法吗?

最佳答案

您没有关闭此:

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"));
}

准备好的语句也需要关闭,并且在所有这些方法中都缺少 try/catch/finally 以防止资源泄漏。我强烈建议不要直接使用 JDBC,因为它很难使用。

关于java - PreparedStatementexecuteUpdate()更新错误记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com