行锁的3种算法
锁是针对索引加锁,如果查询条件无索引,全表扫描、全表锁。不讨论!
1.Record LOCK 单行记录上的锁
2.Gap LOCK 间隙锁,锁定一个范围,但不包含记录本身
3.Next-KEY Lock:Gap LOCK+Record Lock,锁定一个范围,并且锁定记录本身
Innodb对于行的查询都是采用Next-KEY Lock,但是当查询索引时含有唯一索引时,Innodb会对Next-KEY lock进行优化,降级为Record LOCK。仅锁住索引本身而非范围。
创建表
CREATE TABLE `t_student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ;
普通索引
数据库空表无记录
步骤
sessionA
sessionB
1
begin;
2
begin;
3
select * from t_student where name='xm' for update;
4
insert into t_student(name) values ('xm');
-- 锁等待
5
commit