gpt4 book ai didi

Java MySQL事务和executeBatch

转载 作者:行者123 更新时间:2023-11-29 01:04:09 25 4
gpt4 key购买 nike

我遇到了一个我无法解决的问题。

我有以下 SQL 代码片段,我在其中将多行插入到表中。重要的是不要在异常中添加任何行。

代码按预期工作,但如果删除回滚部分,则会在异常时添加一些行,即使 connection.commit();永远不会被调用。这是为什么?

我担心的是:如果我的应用程序在调用批量插入时被操作系统终止,从而永远不会调用回滚部分,会发生什么情况。我的测试表明在这种情况下没有插入任何内容。但是,如果删除了回滚部分,我仍然很困惑为什么在异常情况下会插入一些行。

有什么提示吗?

    Connection connection = null;
PreparedStatement stmt = null;

try {
connection = DBConnectionFactory.getInstance().getConnection(JDNI);
connection.setAutoCommit(false);

stmt = connection.prepareStatement(
"INSERT INTO " + TABLE_PREFIX + TABLE_OUTBOX + "...");

// add multiple statements

stmt.executeBatch();

connection.commit();

} catch (Exception ex) {
try {
log.debug(ex);
log.debug("rolling back insert message batch");
connection.rollback();
log.debug("rollback success");
} catch(Exception e) {
log.debug("unable to rollback", e);
}
throw new TranquilityException("could not insert endpoints!!", ex);
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (Exception ex) {
log.warn("Could not close sql statement", ex);
}
}
if (connection != null) {
try {
connection.setAutoCommit(true);
connection.close();
} catch (Exception ex) {
log.error("Could not close sql connection", ex);
}
}
}
}

最佳答案

我认为发生这种情况有两个原因:

  • 首先,您似乎正在使用连接池。在这个在这种情况下,您的连接将被重新使用。如果你返回一个连接一个未提交的事务到池中,并且该连接由稍后的另一种方法,事务可能会被提交当后面的方法被提交时。

  • 第二个(也是更有可能的)是在你的 finally block 中,你是设置 connection.setAutoCommit(true);当您的方法完成时,这将导致您连接中的所有内容都被刷新。我知道您需要为连接池执行此操作,但您应该确保在执行此操作之前,您的连接处于已完成状态。

关于Java MySQL事务和executeBatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12707361/

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