韩顺平 零基础30天学会Java
事务介绍
基本介绍
- JDBC 程序中一个Connection对象创建时,默认情况下是自动提交事务:每次执行一个SQL语句时,如果执行成功,就会向数据库自动提交,而不能回滚
- JDBC程序中为了能让多个SQL语句作为一个整体执行,需要使用事务
- 调用Connection的setAutoCommit(false)可以取消自动提交事务
- 在所有的SQL语句执行成功之后调用Connection的commit()方法提交事务
- 在其中的某个操作失败,或者出现异常时,调用Connection的rollback(),方法回滚事务
public class Transaction_ {
public static void main(String[] args) {
}
@Test
public void useTransaction(){
//得到连接
Connection connection = JDBCUtils.getConnection();
//设置sql
String sql="update account set balance=balance-100 where id=1";
String sql1="update account set balance=balance+100 where id=2";
//创建preparedstatement
PreparedStatement preparedStatement=null;
try {
//将connection设置为不自动提交
connection.setAutoCommit(false);
//执行第一条sql
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
//执行第二条sql
preparedStatement=connection.prepareStatement(sql1);
preparedStatement.executeUpdate();
//提交事务
connection.commit();
} catch (SQLException e) {
//在这里有机会进行回滚,即撤销执行的sql,默认回滚到事务开始的地方
System.out.println("事务发生异常,撤销事务");
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
throw new RuntimeException(e);
}finally {
JDBCUtils.close(null,preparedStatement,connection);
}
}
}