Java Mysql 简明教程

Java & MySQL - Transactions

如果您的 JDBC 连接处于自动提交模式(默认如此),那么在每个 SQL 语句完成后,它都会提交到数据库。

If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion.

对于简单的应用程序,这可能很好,但有三个原因会导致你想关闭自动提交并管理自己的事务:

That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions −

  1. To increase performance.

  2. To maintain the integrity of business processes.

  3. To use distributed transactions.

事务使你能够控制数据库应用更改的时间和方式。它将单独的 SQL 语句或一组 SQL 语句视为一个逻辑单元,如果其中一条语句引发故障,则整个事务就会失败。

Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails.

要启用手动事务支持而非 JDBC 驱动程序默认使用的自动提交模式,请使用 Connection 对象的 setAutoCommit() 方法。若要 setAutoCommit( ) 传递布尔值 false,则可以关闭自动提交。你可以传递布尔值 true 来重新打开它。

To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object’s setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.

例如,如果你有一个名为 conn 的 Connection 对象,则编写以下代码来关闭自动提交:

For example, if you have a Connection object named conn, code the following to turn off auto-commit −

conn.setAutoCommit(false);

Commit & Rollback

一旦完成更改,并且你希望提交更改,请按照如下方式调用连接对象的 commit() 方法:

Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −

conn.commit( );

否则,若要回滚对使用 conn 命名的 Connection 对数据库作出的更新,则使用以下代码:

Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −

conn.rollback( );

Using Savepoints

新的 JDBC 3.0 Savepoint 接口为你提供了额外的交易控制。

The new JDBC 3.0 Savepoint interface gives you the additional transactional control.

当你设置保存点时,你要在事务中定义一个逻辑回滚点。如果在保存点之后发生错误,则可以使用回滚方法来撤消所有更改或仅撤消保存点之后作出的更改。

When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint.

Connection 对象有两个可帮助你管理保存点的新方法:

The Connection object has two new methods that help you manage savepoints −

  1. setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.

  2. releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.

有一个 rollback (String savepointName) 方法,它将工作回滚到指定的保存点。

There is one rollback (String savepointName) method, which rolls back work to the specified savepoint.