Innodb锁机制
共享锁(S锁):假设事务T1对数据A加上共享锁,那么事务T2可以读数据A,不能修改数据A。
排他锁(X锁):假设事务T1对数据A加上排他锁,那么事务T2不能读数据A,不能修改数据A。
共享锁:又称S(share)锁,读锁
一个sql会话加了共享锁后其他会话也可以查询
示例:
会话1:
use test;
begin
select * from isolation_test lock in share mode
会话2:
use test;
select * from isolation_test lock in share mode
可以查询出数据
如果执行更新操作则会阻塞
update isolation_test set money=22 where id = 1

只有会话1提交或回滚后会话2的更新操作才能成功
排它锁:X锁,读锁:
会话1:
begin
update isolation_test set money=23 where id = 1 //排它锁
会话2:
select * from isolation_test lock in share mode //共享锁
会话2的查询会阻塞,只有等到会话1提交后才能查到数据,因为会话1已经对数据加了排它锁,会话2就不能再加共享锁.
行锁,表锁:
如果用索引列做where条件,innodb加的是行锁,如果用非索引列做where条件,innodb加的是表锁
临键锁,间隙锁:
where 后的条件如果用索引列确定了一个范围,就会在这个范围上加临键锁(范围内有数据)或间隙锁(范围内没数据)
select的加锁情况:
select * from table where id = ?;执行的是快照读,读的是数据库记录的快照版本,是不加锁的
select * from table where id = ? lock in share mode; 对读取记录加共享锁
select * from table where id = ? for update 对读取记录加排它锁
浙公网安备 33010602011771号