import com.atguigu1.util.JDBCUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
public class exe {
@Test
public void exe() {
Connection conn = null;
try {
// 1.获取数据库连接
conn = JDBCUtils.getConnection3();
// 2.开启事务
conn.setAutoCommit(false);
// 3.进行数据库操作
QueryRunner runner=new QueryRunner();
String sql1 = "update user_table set balance = balance - 100 where user = ?";
runner.update(conn, sql1, "AA");
// 模拟网络异常
//System.out.println(10 / 0);
String sql2 = "update user_table set balance = balance + 100 where user = ?";
runner.update(conn, sql2, "BB");
// 4.若没有异常,则提交事务
conn.commit();
} catch (Exception e) {
e.printStackTrace();
// 5.若有异常,则回滚事务
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
//6.恢复每次DML操作的自动提交功能
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
//7.关闭连接
DbUtils.closeQuietly(conn);
}
}
}