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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值