数据库排它锁共享锁死锁行级锁表级锁

1)排它锁
新建两个连接
在第一个连接中执行以下语句
begin tran
update table1
set A='aa'
where B='b2'
waitfor delay '00:00:30' --等待30秒
commit tran
在第二个连接中执行以下语句
begin tran
select * from table1
where B='b2'  
commit tran  

若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待30秒  

2)共享锁
在第一个连接中执行以下语句
begin tran
select * from table1 holdlock -holdlock人为加锁
where B='b2'  
waitfor delay '00:00:30' --等待30秒
commit tran  

在第二个连接中执行以下语句
begin tran
select A,C from table1
where B='b2'  
update table1
set A='aa'
where B='b2'  
commit tran  

若同时执行上述两个语句,则第二个连接中的select查询可以执行
而update必须等待第一个事务释放共享锁转为排它锁后才能执行 即要等待30秒  

3)死锁
增设table2(D,E)
D E
d1 e1
d2 e2
在第一个连接中执行以下语句
begin tran
update table1
set A='aa'
where B='b2'  
waitfor delay '00:00:30'
update table2
set D='d5'
where E='e1'  
commit tran

在第二个连接中执行以下语句
begin tran
update table2
set D='d5'
where E='e1'  
waitfor delay '00:00:10'
update table1
set A='aa'
where B='b2'  
commit tran  

同时执行,系统会检测出死锁,并中止进程  

4)行级锁:
select * from userinfo for update;
这时候可以锁定选中的所有行

如果已经被锁定,就不用等待
select * from userinfo for update nowait;

如果已经被锁定,更新的时候等待5秒
select * from userinfo for update wait 5;

5)表级锁:
行共享:允许用户进行任何操作,禁止排他锁
lock table userinfo in row share mode;

行排他:允许用户进行任何操作,禁止共享锁
lock table userinfo in row exclusive mode;

6)共享锁:其他用户只能看,不能修改
lock table userinfo in share mode;

7)共享行排他:比共享锁有更多限制
lock table userinfo in share row exclusive mode;

8)排他锁:其他用户只能看,不能修改,不能加其他锁
lock table userinfo in exclusive mode;
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值