SELECT语句中的for update的用法(锁的运用)

 
SELECT 语句中的 for update (以及 lock in share mode) 的用法试验。
作用:
当一方锁定后,另一方的操作(update),会等到前一方的commit后才执行.
 
这个语句限制在事务表的其他连接上进行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 是一样的原理。
 
(2)
由于InnoDB预设是Row-Level Lock,所以只有「明确」的指定主键,MySQL才会执行Row lock (只锁住被选取的资料例) ,否则MySQL将会执行Table Lock (将整个资料表单给锁住)。

举个例子:

假设有个表单products ,里面有id跟name二个栏位,id是主键。

例1: (明确指定主键,并且有此笔资料,row lock)
SELECT * FROM products WHERE id='3' FOR UPDATE;

例2: (明确指定主键,若查无此笔资料,无lock)
SELECT * FROM products WHERE id='-1' FOR UPDATE;

例2: (无主键,table lock)
SELECT * FROM products WHERE name='Mouse' FOR UPDATE;

例3: (主键不明确,table lock)
SELECT * FROM products WHERE id<>'3' FOR UPDATE;

例4: (主键不明确,table lock)
SELECT * FROM products WHERE id LIKE '3' FOR UPDATE;

注1: FOR UPDATE仅适用于InnoDB,且必须在交易区块(BEGIN/COMMIT)中才能生效。
注2: 要测试锁定的状况,可以利用MySQL的Command Mode ,开二个视窗来做测试。

你可能感兴趣的:(职场,休闲)