泉友 发表于 2023-6-10 05:50:23

数据库事务隔离级别

标准隔离级别

读未提交、读已提交、可重复读、串行化串行化

对事务中所有读写的数据加上读锁、写锁、范围锁。所以冲突的事务必须同步执行。//console1
start transaction ;
select * from transaction_test where `key`=1;
update transaction_test set name='newTest' where `key`=1;
//console2
start transaction ;
select * from transaction_test where `key`=1;(由于事务1没有释放写锁,所以这里的查询会阻塞
如果等待时间过长,会报如下的错误;如果事务1只是查询,那么事务2也可以查询)
Lock wait timeout exceeded; try restarting transaction
//console1
commit ;(提交完之后如果事务2没有等待超时,那么会立即执行)
//console2;
commit ;可重复读

核心是只对事务中所有读写的数据加上读锁、写锁,不加范围锁。相比于读已提交,由于对整个事务都加上了读锁,避免其他事务可以进行更新,进而保证同一个事务多次读到的数据都是没有被修改过的数据。----避免可重复读----
name初始值为init
//console1
start transaction ;
select * from transaction_test where `key`=1;(查询结果是init)
//console2
start transaction ;
update transaction_test set name='test' where `key`=1;
(理论上,由于事务1已经获取了读锁,事务2这里添加写锁应该是添加不上的,应该是阻塞中才对;
但是,实操发现,执行成功了,且在事务2中通过下面这个语句查询是test,这应该也是mvcc导致的
select * from transaction_test where `key`=1;
//console1
select * from transaction_test where `key`=1;
console1的第2次查询,查询结果和第一次一样,还是init
另外,事务2都获得写锁了,怎么能允许你事务1再去获得读锁
commit ;
//console2
commit ;相比于串行化,由于没有加范围锁,会引发一种叫幻读的情况所谓幻读是指在同一个事务中,第一次查询id
页: [1]
查看完整版本: 数据库事务隔离级别