显式锁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才能獲得行鎖 再查詢判斷。
?
轉載于:https://www.cnblogs.com/mryangbo/p/10805121.html
總結
以上是生活随笔為你收集整理的显式锁select for update 用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python小白——进阶之路——day6
- 下一篇: [Git] 001 初识 Git 与 G