1. 程式人生 > >資料庫排它鎖共享鎖死鎖行級鎖表級鎖

資料庫排它鎖共享鎖死鎖行級鎖表級鎖

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;