MySQL锁行锁表

select..for update; 给数据库表手动上锁

--锁行
Begin
; Select restnum from book where id =1 for update; --给 id=1 的行加上排它锁且 id 有索引
Update book set restnum=restnum-1 where id=1 ; Commit;

-- 锁表
BEGIN;
SELECT * FROM frm_globalsettings WHERE  KeyCode='WxDepartmentMaxValue' FOR UPDATE ;
UPDATE frm_globalsettings SET keyvalue=keyvalue+1 WHERE KeyCode='WxDepartmentMaxValue';
COMMIT;
 

   这条语句会开启一个session,直到这个session Commit,其他session才能执行更新、插入、删除操作,对查询没有影响,但是这张表再不能开启其他select..for update;

   使用情况:使用count(*)作为流水号字段的值时,在高并发情况下容易出现重复,此时用select..for update;执行插入前锁住这张表来保证流水号不重复,使用时把select..for update;与执行insert、update、delete 的语句放在service(业务层)下一个方法中,如果放在service下的两个以上方法中,controller类调用一个方法结束后会自动执行下commit,达不到锁住表的效果。

this.DaoBase.ExecuteCommand("select * from enrollment_student_info for update");//先开启select..for update把表锁上,后面过来的事物只能先等这个事物执行完了再执行
object res = this.DaoBase.ExecuteScalar("select count(*) from enrollment_student_info");
this.DaoBase.ExecuteNonquery("Insert...");
原文地址:https://www.cnblogs.com/xbblogs/p/5336578.html