顯式鎖select for update 用法


兩個事務操作:

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才能獲得行鎖 再查詢判斷。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM