基本介绍:
1.JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务,每次执行一个SQL语句时,如果执行成功则会向数据库自动提交,而不能回滚
2.JDBC程序中为了让多个SQL语句作为一个整体执行,需要使用事务
3.调用Connection的setAutoCommit(false)可以取消自动提交事务
4.在所有的SQL语句都成功执行后,调用Connection的commit();方法提交事务
5.在其中某个操作失败或出现异常时,调用Connection的rollback();方法回滚事务
package com.jh.transaction_;
//演示在JDBC中如何使用事务
import com.jh.jdbc.JDBCUtils;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Transaction_ {
@Test
public void noTransaction(){
//1.得到连接
Connection connection = null;
//组织SQL语句
String sql = "update accout set balance = balance - 100 where id = 1";
String sql02 = "update accout set balance = balance + 100 where id = 2";
PreparedStatement preparedStatement = null;
//创建PreparedStatement对象
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();//执行
int i = 1/0;
preparedStatement = connection.prepareStatement(sql02);
preparedStatement.executeUpdate();//执行
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
}
//使用事务
@Test
public void Transaction(){
//1.得到连接
Connection connection = null;
//组织SQL语句
String sql = "update accout set balance = balance - 100 where id = 1";
String sql02 = "update accout set balance = balance + 100 where id = 2";
PreparedStatement preparedStatement = null;
//创建PreparedStatement对象
try {
connection = JDBCUtils.getConnection();//默认情况下,connection自动提交
//将connection设置为不自动提交
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();//执行
int i = 1/0;
preparedStatement = connection.prepareStatement(sql02);
preparedStatement.executeUpdate();//执行
//提交事务
connection.commit();
} catch (SQLException e) {
System.out.println("发送异常,进行回滚...");
try {
connection.rollback();//开始回滚(撤销执行的SQL),默认回滚到事务开始的状态
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new RuntimeException(e);
}finally {
//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
}
}




可以看出:tom减少一百,而jason并未增加一百


当有异常发生时,两条SQL语句都不会去执行