1.事务简介
2.事务操作
--转账操作(张三给李四转账1000)--正常情况
--1. 查询张三账户余额
select * from account where name = '张三';
--2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';
--3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';
--转账操作(张三给李四转账1000)--异常情况
--1. 查询张三账户余额
select * from account where name = '张三';
--2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';
#添加错误
程序抛出异常
--3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';
#执行之后就会出现错误,张三的钱扣除了1000,而李四的钱并没有加上1000
查看/设置事务提交方式
select @@autocommit;
#0表示手动提交,必须执行commit操作sql语句才会执行;默认是1,自动提交
set @@autocommit = 0;
提交事务
commit;
回滚事务
rollback;
添加事务:
--转账操作(张三给李四转账1000)
select @@autocommit;
set @@autocommit = 0;
--1. 查询张三账户余额
select * from account where name = '张三';
--2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';
#添加错误
程序抛出异常
--3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';
#正常情况
commit;
#出错之后
rollback;
开启事务
start transaction;
上述的添加事务还可以这样操作,不用手动设置@@autocommit为0
--转账操作(张三给李四转账1000)
start transaction
--1. 查询张三账户余额
select * from account where name = '张三';
--2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';
#添加错误
程序抛出异常
--3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';
#正常情况
commit;
#出错之后
rollback;
3.事务四大特性
并发事务问题:
4.事务隔离级别
注意:事务隔离级别越高,数据越安全,但是性能越低