mysql4.X的for update

来源:互联网 发布:淘宝上超好吃的零食 编辑:程序博客网 时间:2024/05/19 22:27
 
在MySQL中,可以使用select ... for update来锁定数据。不过这个用法有一些注意事项:
 
1) for update 是基于InnoDB的;
2) for update 必须在事务块中才能生效;
    start transaction;
    select ...... for update;
    commit;
3) 由于InnoDB的预设值是 Row-Level Lock, 所以如果:
    一个InnoDB的表设定了 primary key;
    在select语句中使用了明确的主键;
才能执行Row-Level Lock,否则会执行Table-Level Lock。
 
例如:
1) 明确指定主键,且有此记录;
select * from Table1 where PK_field=22 for update;
这样是Row-Level Lock;
 
2) 明确指定主键,且无此记录;
select * from Table1 where PK_field=22 for update;
这样是non-lock;
 
3) 不明确指定主键;
select * from Table1 where PK_field!=22 for update;
或者
select * from Table1 where PK_field like '22' for update;
这样是table-Level Lock;