set autocommit=0;
select * from lock in share mode; (不加where 则锁定所有记录共享锁)
当前会话可以更新删除 插入记录
其他会话可以select lock in share mode,select, 不能更新删除 锁定的行或者表 必须等待当前会话commit rollback (注意 select for update 可能加的是表锁)
select * from t for update;
当前会话更新插入删除
其他会话可以select , (在数据库 默认可重复读隔离级别)
lock in share mode,for update, update,delete则需要等待。因为当前会话已经锁定的行或者表,等待当前会话commit rollback
注意mysql的行锁 是针对索引条件检索的,如果检索字段木有索引,则加表锁(oracle是对数据加锁)
session1:
select * from where id=2 for update
session2:
select * from where name=2
如果以上两个会话使用不同索引检索字段,但是对应同一个记录 也会最终冲突(使用索引字段 但是执行计划 会根据情况选择全表扫描 则依然是表锁)
注意字符串类型 使用数值 胡自动抛弃索引检索,改用全表
session1
select * from where id=1 for update
session2
select * from where id=1 for update (如果id=1的记录不存在 则 session2 不会阻塞)
select * from table_sfu where a = 1 for update wait 3; 可以控制锁等待多少秒
http://blog.csdn.net/xifeijian/article/details/20313977 (此文章中有部分错误)