gpt4 book ai didi

java - 在 JDBC 中,当 autocommit 为 false 且未设置显式保存点时,回滚是好风格还是浪费?

转载 作者:IT老高 更新时间:2023-10-28 20:51:50 24 4
gpt4 key购买 nike

假设你有以下代码:

Connection conn;
try
{
conn = ... // get connection
conn.setAutoCommit(false);

... // Do some modification queries and logic

conn.commit()
} catch(SQLException e)
{
conn.rollback() // Do we need this?
conn.close()
}

在这段代码中,如果出现异常,是关闭连接(因为自动提交已关闭)还是显式回滚然后关闭连接更好?没有存档点。

我觉得添加回滚调用可能有意义,因为:

1) 将来有人可能会添加保存点但忘记添加回滚

2) 提高可读性

3) 它不应该花费任何东西,对吧?

但显然,这些都不是特别引人注目。有什么标准做法吗?

注意:我知道在关闭和回滚时需要重复尝试/捕获。我实际上有一个中间件可以抽象数据库访问并处理它,但我想知道添加它是否是多余的。

最佳答案

正常的成语如下:

public void executeSomeQuery() throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);

try (PreparedStatement statement = connection.prepareStatement(SOME_SQL)) {
// Fire transactional queries here.

connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}

请注意,Java 7 的 try-with-resources statementtry block 完成时,总是在资源上隐式调用 close(),就好像它发生在 finally 中一样。

调用 rollback() 在涉及池连接时也是强制性的。也就是说,它将重置连接的事务状态。池连接的 close() 不会这样做,只有 commit()rollback() 会这样做。不调用 rollback() 可能会导致池连接的下一个租约仍将在其内存中保留上一个事务的(成功)查询。

参见 Connection#close() 的 javadoc (重点不是我的):

It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the close method. If the close method is called and there is an active transaction, the results are implementation-defined.

关于java - 在 JDBC 中,当 autocommit 为 false 且未设置显式保存点时,回滚是好风格还是浪费?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3160756/

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