gpt4 book ai didi

java - 提交或 conn.setAutoCommit(true)

转载 作者:IT王子 更新时间:2023-10-28 23:48:07 25 4
gpt4 key购买 nike

我注意到一些程序员使用 COMMIT 其他使用 conn.setAutoCommit(true); 来结束事务或回滚那么使用一个而不是另一个?

主要区别在哪里?

conn.setAutoCommit(true);

结束

statement.executeQuery(query);
statement.commit();

最佳答案

您通常应该使用 Connection.commit() 而不是 Connection.setAutoCommit(true) 来提交事务,除非您想从使用事务切换到autoCommit 的“每个语句的事务”模型。

也就是说,在事务中调用 Connection.setAutoCommit(true) 将提交事务(如果驱动程序符合 JDBC 4.1 规范的第 10.1.1 节)。但是,如果您打算在那之后留在 autoCommit 中,您真的应该这样做,因为在连接上启用/禁用 autoCommit 可能比简单提交具有更高的连接开销(例如,因为它需要在事务管理器之间切换,做额外的检查等)。

您还应该使用 Connection.commit(),而不是使用原生 SQL 命令 COMMIT。如连接文档中所述:

Note: When configuring a Connection, JDBC applications should use the appropritate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available.

问题是像 commit()setAutoCommit(boolean) 这样的命令可能会在后台做更多的工作,比如关闭 ResultSets并关闭或重置 Statements。使用 SQL 命令 COMMIT 将绕过这一点,并可能使您的驱动程序/连接进入错误状态。

关于java - 提交或 conn.setAutoCommit(true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10457335/

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