gpt4 book ai didi

java - jdbc 自动提交(false) 不起作用

转载 作者:行者123 更新时间:2023-11-30 02:30:40 25 4
gpt4 key购买 nike

有一些我不明白的 java.sql.Connection.commit()

我使用 Derby(Java DB) 作为数据库服务器。

当我执行 setAutoCommit(false) 时,我希望在显式调用 commit() 方法之前我的查询不会工作。但事实上,即使我不调用 commit(),它仍然会提交。当我在表上调用 select * 来打印内容时,我可以看到即使我没有显式提交查询,行也已添加。

有人可以给我一些解释吗?

    con.setAutoCommit(false);
PreparedStatement updateHair = null;
PreparedStatement addMan = null;
try {

String updateString =
"update PERSONNE " +
"set haircolor = 'RED' where haircolor = 'SHAVE'";

String updateStatement =
"insert into personne values " +
"(3,'MICHEL','SHAVE')";

addMan = con.prepareStatement(updateStatement);
addMan.executeUpdate();

updateHair = con.prepareStatement(updateString);
updateHair.executeUpdate();

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

最佳答案

自动提交意味着每个单独的SQL语句被视为一个事务,并在执行后立即自动提交。默认情况下,SQL 语句在完成时提交,而不是在执行时提交。当检索到所有结果集和更新计数时,语句即完成。然而,在几乎所有情况下,语句都会在执行后完成并因此提交。

允许两个或多个语句组合成一个事务的方法是禁用自动提交模式。

con.setAutoCommit(false);

当自动提交模式被禁用时,只有显式调用commit方法才会提交SQL语句。上次调用方法 commit 之后执行的所有语句都包含在当前事务中,并作为一个单元一起提交。

-- EDIT_1

可能会提交更新,因为您在未调用 rollback() 的情况下关闭了连接。

如果在没有显式提交或回滚的情况下关闭连接,则行为取决于数据库。

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.

Connection.close()

关于java - jdbc 自动提交(false) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357848/

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