MYSQL学习笔记27: 事务
事务

数据准备
create table account(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
money int comment '余额'
) comment '账户表';
insert into account(id,name,money) values (null,'张三',2000),(null,'李四',2000);

转账
-- 查询张三账户余额
select * from account where name = '张三';
-- 张三-1000
update account set money = money - 1000 where name = '张三';
-- 李四+1000
update account set money = money + 1000 where name = '李四';

如果转账过程出错
update account set money = money - 1000 where name = '张三'; -- 张三-1000
这是一个错误语句, 程序抛出异常...
update account set money = money + 1000 where name = '李四'; -- 在上一语句出错, 该语句没有被执行, 张三-1000, 但是没有转账给李四

通过事务回滚数据
方式1
关闭自动提交, 设置手动提交, 在commit前, 表中的实际数据不会改变
-- 查询当前自动提交模式(默认为1, 自动提交)
select @@autocommit;
-- 关闭自动提交, 设置为手动提交
set @@autocommit = 0;
/*
业务代码
*/
-- 程序未出错,手动提交
commit;
-- 如果报错, 不要提交, 回滚数据
rollback;
实例
set @@autocommit = 0; -- 设置为手动提交
update account set money = money - 1000 where name = '张三'; -- 张三-1000
这是一个错误语句, 程序抛出异常...
update account set money = money + 1000 where name = '李四'; -- 在上一语句出错, 该语句没有被执行, 张三-1000, 但是没有转账给李四
commit; -- 程序未出错, 手动提交
rollback; -- 程序出错, 不必提交, 回滚数据
方式2
显式开启事务, 保持自动提交, 通过start transaction或begin语句开启事务
start transaction; -- 开始事务
/*
业务代码
*/
commit; -- 程序未出错,手动提交
rollback; -- 如果报错, 不要提交, 回滚数据
实例
set @@autocommit = 1; -- 设置提交模式为默认的自动提交
start transaction; -- 开启事务
update account set money = money - 1000 where name = '张三'; -- 张三-1000
这是一个错误语句, 程序抛出异常...
update account set money = money + 1000 where name = '李四'; -- 在上一语句出错, 该语句没有被执行, 张三-1000, 但是没有转账给李四
commit; -- 程序未出错,手动提交
rollback; -- 如果报错, 不要提交, 回滚数据

浙公网安备 33010602011771号