# 使用事务 

__*使用 Java 控制事务*__

+ 使用`try-catch` 
  + `try`
    + 禁用 `autocommit` 
    + 执行 `DML` 
    + `commit`
    + 启用 `autocommit` 
  + `catch`
    + `try`
      + DML 失败后的动作
      + `rollback`
      + 启用 `autocommit` 
    + `catch`
      + 处理回滚失败
------------------------------------------------------
演示脚本:

对于 macOS 和 Linux:https://github.com/pingcap/tidb-course-201-lab/blob/master/scripts/09-demo-jdbc-execute-update-tx-01-show.sh

对于 Windows:https://github.com/pingcap/tidb-course-201-lab/blob/master/scripts/09-demo-jdbc-execute-update-tx-01-show.bat


我们使用 setAutoCommit (false) 通过禁用自动提交来启动事务。

该程序执行 DML。如果更改成功,则会通过 commit () 方法将更改保留到数据库中。

如果第一个 try 块中的 DML 语句失败,则程序会引发异常,该异常会在 catch 块中捕获。

然后,程序应该做任何必要的事情来处理业务逻辑中的 DML 故障,或者只是显示一条消息并尝试使用 rollback () 方法进行回滚。它还会重新启用自动提交模式。

回滚本身在第二个 try 块中执行,因此,如果回滚失败,则会引发异常并再次捕获。


```
try {
 connection.setAutoCommit (false);
 Statement s = conn.createStatement ();
 s.executeUpdate ("DML ...");
 s.executeUpdate ("DML ...");
  s.close ();
 conn.commit ();
 conn.setAutoCommit (true);
}
catch (SQLException e) {
 // TODO custom function 
 try	{
   conn.rollback ();
   conn.setAutoCommit (true);
 }
 catch (SQLException er) {
   // TODO custom function 
 }
}
```
