gpt4 book ai didi

java - 如果 java.sql.Connection#commit() 抛出异常,是否需要回滚?

转载 作者:太空狗 更新时间:2023-10-29 22:38:47 26 4
gpt4 key购买 nike

根据 JAVA documentation , Connection#commit() 可以抛出 SQLException。我的问题是在这种情况下是否仍应发出回滚。

例如:

Connection con = null;
try {
// assume this method returns an opened connection with setAutoCommit(false)
con = createConnection();

// do DB stuff

con.commit();
} catch (SQLException e) {
if (con != null) {
// what if con.commit() failed, is this still necessary,
// will it hurt anything?
con.rollback();
}
} finally {
if (con != null) {
con.close();
}
}

我实际上将 con.rollback() 调用包装到另一个忽略它抛出的任何异常的方法中,所以我认为我在这里没问题。我只是想知道这是否是处理事情的最佳方式。

最佳答案

根据 Java 1.6 JDBC docs,即使提交失败,回滚也很重要:

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.

这意味着如果您没有显式调用回滚,某些 JDBC 实现可能会在关闭连接之前调用提交。

回滚的另一个很好的理由是 Xepoch 所建议的,并且在使用连接池时它更为重要。当从连接池获取连接时,大多数实现将在为您提供连接之前执行 connection.setAutoCommit(defaultAutoCommit) 并且根据 JavaDocs:

If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed

如果 connection.rollback() 抛出异常 - 那么这是一个棘手的问题......

关于java - 如果 java.sql.Connection#commit() 抛出异常,是否需要回滚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3790922/

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