jdbc autocommit(false) doesnt work

落花浮王杯 提交于 2020-05-29 13:01:29

问题


There is something i don't understand with java.sql.Connection.commit().

I am using Derby(Java DB) as database server.

when I do a setAutoCommit(false) , I expect my query not to work before I explicitly call the commit() method. but in fact, it still commit even if I don't call commit(). when I call a select * on my table to print the content, I can see that the rows have been added even though i didn't explicitly commit the query.

Could someone give me some explanation please?

    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();
    }

回答1:


Auto-commit means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. The default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.

The way to allow two or more statements to be grouped into a transaction is to disable the auto-commit mode.

con.setAutoCommit(false);

When the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit.

-- EDIT_1

Updates may be committed because you're closing your Connection without calling rollback().

If a Connection is closed without an explicit commit or a rollback the behaviour depends on database.

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()



来源:https://stackoverflow.com/questions/44357848/jdbc-autocommitfalse-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!