SELECT 语句中的 for update (以及 lock in share mode

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 是一样的原理。

本文出自 “上帝,咱们不见不散!” 博客,转载请与作者联系!

你可能感兴趣的:(update,select,for,语句,休闲)