分类: Mysql/postgreSQL
2008-02-15 10:16:58
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 MODE 和 FOR UPDATE 是一样的原理。
shuiping562014-05-21 12:20:35
这两个的用法还是有细微的差别吧,“这一段 For another example, consider an integer counter field in a table CHILD_CODES, used to assign a unique identifier to each child added to table CHILD. Do not use either consistent read or a shared mode read to read the present value of the counter, because two users of the database could see the same val