显式锁select for update 用法
兩個(gè)事務(wù)操作:
set autocommit=off;
A:
begin;
select * from students where id=1 for update;
B:
begin;
select * from students where id=1;
顯示結(jié)果(直接查詢,無需獲得鎖)
select * from students;
顯示結(jié)果
select * from students where id=2 for update ;
顯示結(jié)果
select * from students where id=1 for update;
等待(事務(wù)A提交后才會(huì)獲得該行行鎖)
?
案例:
轉(zhuǎn)賬操作中需要判斷余額是否足夠
begin;
select balance from account where id=1;? ①
(對(duì)余額進(jìn)行判斷,余額不做的不更新操作)
update account set balance=balance-100 where id=1; ②
update account set balance=balance+100 where id=2;?
commit;
多線程下,會(huì)有多個(gè)事務(wù)并發(fā)訪問數(shù)據(jù)庫。
假設(shè)余額150,事務(wù)a可以執(zhí)行到①判斷余額充足,切換線程執(zhí)行事務(wù)b到①并判斷余額充足,最后都提交后,id為1的賬戶余額為-50;所以必須讓整個(gè)事務(wù)操作保持原子性。
修改①為:select balance from account where id=1 for update;對(duì)該記錄加行鎖。當(dāng)事務(wù)a執(zhí)行完提交釋放行鎖時(shí)事務(wù)b才能獲得行鎖 再查詢判斷。
?
轉(zhuǎn)載于:https://www.cnblogs.com/mryangbo/p/10805121.html
總結(jié)
以上是生活随笔為你收集整理的显式锁select for update 用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python小白——进阶之路——day6
- 下一篇: [Git] 001 初识 Git 与 G