事务操作 mysql的事务操作
事务操作
举例:
create table my_account(
id int unsigned not null primary key auto_increment,
account varchar(16) not null unique,
name varchar(10) not null,
money decimal(20,2)) charset utf8;
insert into my_account values
(1 , "0000000000000000" , "张三", 1000),
(2 , "1111111111111111" , "李四", 2000),
(3 , "2222222222222222" , "王五", 3000);
-- 如果此时进行转账操作
update my_account set money = money - 500 where id = 1;
-- 如果停电 就会出问题:张三转账给某人了 可是某人没收到 而且张三也亏了500元
/****************************************************************************/
-- 事务操作 (1.手动提交 2. 自动提交(默认)
start transaction; //开启事务操作
-- 转账
update my_account set money = money - 500 where id = 1;
-- 查询数据
select * from my_account; (查看到已经扣了500 其实这是 事务管理 操作了的)
-- 此时停电 会 回滚
-- 转账
update my_account set money = money + 500 where id = 2;
-- 手动提交
commit;
/*******************************************************************************/
-- 有关回滚点
-- 开启事务
start transaction;
-- 2 3转账给1 500元
update my_account set money = money - 500 where id = 2;
-- 设置回滚点
savepoint sp1;
update my_account set money = money - 600 where id = 3; //这步做错了
-- 回滚
rollback to sp1;
图片展示: