use db2;
事务
-- 创建账户表
create table account(
id int primary key auto_increment,
name varchar(10),
balance double
);
-- 查看表
desc account;
-- 添加数据
insert into account values (1,'zhangsan',1000),(2,'lisi',1000);
-- 查看看数据
select * from account;
-- 张三给李四转500元
-- 0.开启事务
start transaction;-- 事务回滚到这
-- 1.张三账户余额>500
-- 2.张三账户 - 500
update account set balance = balance - 500 where name = 'zhangsan';
-- 3.李四账户 + 500
-- 出错了 --
update account set balance = balance + 500 where name = 'lisi';
-- 注意:1.开启事务后,没有提交或是回滚的数据是临时的,另一个查询上可以看到真实数据
-- 注意:2.开启事务后,若没有提交,就关闭查询窗口,则默认自动回滚
-- 发现没有问题,提交事务
commit;
-- 发现错误 回滚
rollback;
-- 查看事务默认提交方式
select @@autocommit; -- 1 自动提交 0 手动提交
-- 修改事务默认提交方式
set @@autocommit=0; -- 0 手动提交
set @@autocommit=1; -- 1 自动提交
···
# 隔离级别
```sql
-- 查看数据库事务的隔离级别
select @@tx_isolation; -- 老版本
select @@transaction_isolation;-- 8以上版本
-- 修改数据库事务的隔离级别
-- 临时(虚假),离开此查询,恢复默认值
set transaction_isolation='read-committed';
-- 修改默认值 重新连接后有效
set global transaction isolation level repeatable read;
演示
-- 1.脏读
-- 设置为 读未提交
set transaction_isolation='read-uncommitted';-- 临时(虚假),离开此查询,恢复默认值
start transaction;-- 事务回滚到这
update account set balance = balance - 500 where name = 'zhangsan';
update account set balance = balance + 500 where name = 'lisi';
rollback;