发博文
上帝他爸

yueliangdao0608.blog.chinaunix.net

逆境,是上帝帮你淘汰竞争者的地方!   
个人资料
  • 博客访问:1425049
  • 博文数量:217
  • 博客积分:11261
  • 博客等级:上将
  • 关注人气: 6
  • 注册时间:2006-12-28 14:24:03
订阅我的博客
  • 订阅
  • 订阅到鲜果
  • 订阅到抓虾
  • 订阅到Google
字体大小: 博文
分类: 高可用性

 

SELECT 语句中的 for update (以及 lock in share mode) 的用法试验。
这个语句限制在事务表的其他连接上进行UPDATE或者DELETE操作。
连接1命名为A。
连接2命名为B。
有几个先决条件:
1、当autocommit 系统变量值为off 或者为0 的时候起作用。
2、并且表的引擎是支持事务的,比如INNODB。
3、也可以不管autocommit的执,手动在事务里执行操作,这个时候可能要begin或者start transaction语句了。
4、不要在锁定事务在innodb_lock_wait_timeout规定以外的时间完成。
此时在A连接执行:
mysql> use t_girl;
Database changed
mysql> create table t (id int not null auto_increment primary key, cstr char(40) not null) engine innodb;
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+------------------+

| Tables_in_t_girl |
+------------------+

| t |
+------------------+

1 row in set (0.00 sec)

mysql> insert into t(cstr) values('This is huahua'),('This is not huahua'),('Huahua is a dog,not a person\'s name');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> select * from t;
+----+-------------------------------------+
| id | cstr |
+----+-------------------------------------+
| 1 | This is huahua |
| 2 | This is not huahua |
| 3 | Huahua is a dog,not a person'
s name |
+----+-------------------------------------+

3 rows in set (0.00 sec)

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from t where id = 2 for update;
+----+--------------------+

| id | cstr |
+----+--------------------+

| 2 | This is not huahua |
+----+--------------------+

1 row in set (0.00 sec)
过了一段时间后执行:
mysql> commit;
Query OK, 0 rows affected (0.00 sec)
此时在B连接执行:
mysql> update t set cstr = 'I know huahua is a person' where id =2;
Query OK, 1 row affected, 0 warning (48.91 sec)
Rows matched: 1 Changed: 1 Warnings: 0
这个UPDATE会一直等待A连接执行commit或者rollback才会生效。

mysql> select * from t where id =2;
+----+-----------------------------------------+

| id | cstr |
+----+-----------------------------------------+

| 2 | I know huahua is a person |
+----+-----------------------------------------+

1 row in set (0.00 sec)
此时在A连接上执行:
mysql> select * from t where id = 2;
+----+-----------------------------------------+

| id | cstr |
+----+-----------------------------------------+

| 2 | I know huahua is a person |
+----+-----------------------------------------+

1 row in set (0.00 sec)


LOCK IN SHARE MODEFOR UPDATE 是一样的原理。

 

我的更多文章
[发评论] 评论 重要提示:警惕虚假中奖信息!
  • vyouzhi 2008-06-20 15:49
    这个例子让我知道事务与非事务的区别了
亲,您还没有登录,请[登录][注册]后再进行评论