查看数据库事务隔离级别
mysql> show variables like 'transaction%';
mysql> select @@transaction_isolation;
mysql> SELECT @@GLOBAL.transaction_isolation, @@GLOBAL.transaction_read_only;
mysql> SELECT @@SESSION.transaction_isolation, @@SESSION.transaction_read_only;
修改事务隔离级别的方式
- 由低到高分别为
- read uncommitted (读未提交)
- read committed (读提交)
- repeatable read (重复)
- Serializable (序列化)
1.只在本次会话有效
mysql> set session transaction isolation level read committed;
2.设置全局的事务隔离级别,该设置不会影响当前已经连接的会话,新会话,将使用新设置的事务隔离级别
mysql> set global transaction isolation level read committed;
3.修改配置文件,重启后生效
[mysqld]
transaction-isolation = REPEATABLE-READ
transaction-read-only = OFF
select id,name,count from ent_stock;
select id,name,count from ent_stock lock in share mode;
update ent_stock s set s.count = s.count-1 where s.name = '库存-1';
insert into ent_stock(id,name,count) values(uuid(),'库存-3',1000);
级别 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|
ru | 是 | 是 | 是 |
rc | 否 | 是 | 是 |
rr | 否 | 否 | 是 |
ru | 否 | 否 | 否 |
- Read-Uncommitted
Transication A | Transication B |
---|---|
begin; | begin; |
- | |
- | |
- | |
- | commit; |
- |
- Read-Committed(不可重复读)
1.解决脏读
Transication A | Transication B |
---|---|
begin; | begin; |
- | |
- | |
- | |
- | commit; |
- |
- Repeatable Read(可重复读)
Transication A | Transication B |
---|---|
begin; | begin; |
- | |
- | |
- | |
- | commit |
- |
- 事务A: update ent_stock s set s.count = count-1 where s.name = '库存-1';
- 事务B: update ent_stock s set s.count = count-1 where s.name = '库存-1';
- 事务A给库存-1加了X锁,事务B更新时只能阻塞等待事务A提交后才可提交此次更新,反之同理
- 普通select是查询快照读,select ... lock in share mode 使用当前读,当其他事务有update操作,本事务会阻塞,直到其他事务释放锁