1. 程式人生 > >顯式鎖select for update 用法

顯式鎖select for update 用法

lan 進行 足夠 原子 comm rom nts 會有 spa

兩個事務操作:

set autocommit=off;

A:

begin;

select * from students where id=1 for update;

B:

begin;

select * from students where id=1;

顯示結果(直接查詢,無需獲得鎖)

select * from students;  

顯示結果

select * from students where id=2 for update ;

顯示結果

select * from students where id=1 for update;

等待(事務A提交後才會獲得該行行鎖)


案例:

轉賬操作中需要判斷余額是否足夠

begin;

select balance from account where id=1; ①

(對余額進行判斷,余額不做的不更新操作)

update account set balance=balance-100 where id=1; ②

update account set balance=balance+100 where id=2;

commit;

多線程下,會有多個事務並發訪問數據庫。

假設余額150,事務a可以執行到①判斷余額充足,切換線程執行事務b到①並判斷余額充足,最後都提交後,id為1的賬戶余額為-50;所以必須讓整個事務操作保持原子性。

修改①為:select balance from account where id=1 for update;對該記錄加行鎖。當事務a執行完提交釋放行鎖時事務b才能獲得行鎖 再查詢判斷。

顯式鎖select for update 用法