"set transaction" 是否在自动提交开启时启动事务?

Does "set transaction" start a transaction when autocommit is ON?

我在 AutoCommit ON 模式下使用 Oracle(Java 应用程序使用 JDBC)。

当我将多个 DML 语句作为单个事务执行时,我想我可以这样做:

set transaction read write
update user_tbl set name='mark' where email='m@xyz.com'
update user_tbl set name='ken' where email='k@xyz.com'
--if other things are successful, then:
commit
-- else:
--rollback

然而,似乎每当我最终执行 rollback 时,这些行都有我上述语句的新值。

那么,虽然一开始就执行了set transaction,有没有可能update语句是在AutoCommit ON模式下执行的?

这在文档中有清楚的解释: http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html
http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#setAutoCommit(boolean)

Note: When configuring a Connection, JDBC applications should use the appropriate 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. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.


setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException
Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the method commit or the method rollback. By default, new connections are in auto-commit mode. The commit occurs when the statement completes. The time when the statement completes depends on the type of SQL Statement:

For DML statements, such as Insert, Update or Delete, and DDL statements, the statement is complete as soon as it has finished executing. For Select statements, the statement is complete when the associated result set is closed. For CallableStatement objects or for statements that return multiple results, the statement is complete when all of the associated result sets have been closed, and all update counts and output parameters have been retrieved. NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed. If setAutoCommit is called and the auto-commit mode is not changed, the call is a no-op.


上面的意思是,您的代码在自动提交模式下 运行 等同于:

set transaction read write;
commit; -- invoked by JDBC autocommit
update user_tbl set name='mark' where email='m@xyz.com';
commit; -- invoked by JDBC autocommit
update user_tbl set name='ken' where email='k@xyz.com';
commit; -- invoked by JDBC autocommit
--if other things are successful, then:
commit;
commit; -- invoked by JDBC autocommit