MySQL 串行隔离级别小记

1. 串行加的是行级锁不是表锁

  数据和隔离级别

mysql> select * from t2;
+---+
| a |
+---+
| 1 |
| 2 |
| 5 |
| 6 |
| 7 |
| 9 |
+---+
6 rows in set (5.09 sec)

mysql> show variables like '%isolation%';
+-----------------------+--------------+
| Variable_name         | Value        |
+-----------------------+--------------+
| transaction_isolation | SERIALIZABLE |
| tx_isolation          | SERIALIZABLE |
+-----------------------+--------------+
2 rows in set, 1 warning (0.00 sec)

  事务A:

mysql> begin;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from t2 where a = 2 for update;
+---+
| a |
+---+
| 2 |
+---+
1 row in set (0.00 sec)

  事务B:

mysql> insert into t2 values(3);
Query OK, 1 row affected (0.01 sec)
mysql> insert into t2 values(2);
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

2. 当autocommit=1时,写是否阻塞读

  事务A

mysql> begin;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into t2 values(13);
Query OK, 1 row affected (0.00 sec)

  事务B,不显式开启事务查询。查询的是事务A开启之前的快照

mysql> select *from t2;
+----+
| a  |
+----+
|  1 |
|  2 |
|  3 |
|  5 |
|  6 |
|  7 |
| 11 |
+----+
7 rows in set (0.00 sec)

  事务B,显式开启事务查询

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

mysql> select *from t2;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

  当autocommit=1时,不显式开启事务的读是快照读。

3. 当autocommit=1时,读是否会阻塞写

  3.1 事务B,不显式开启事务查询:

#事务B
mysql> select *from t2;
+----+
| a  |
+----+
|  1 |
|  2 |
|  3 |
|  5 |
|  6 |
|  7 |
| 11 |
| 13 |
+----+
8 rows in set (0.00 sec)

#事务A
mysql> insert into t2 values(15);
Query OK, 1 row affected (0.02 sec)

  3.2 事务B,显式开启事务查询:

#事务B
mysql> begin;
Query OK, 0 rows affected (0.00 sec)
mysql> select *from t2;
+----+
| a  |
+----+
|  1 |
|  2 |
|  3 |
|  5 |
|  6 |
|  7 |
| 11 |
| 13 |
| 15 |
+----+
9 rows in set (0.00 sec)

#事务A
mysql> insert into t2 values(16);
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

   串行隔离级别总结:

  1. 写加的是记录锁。只要不是操作同一条记录,写写互不影响

  2. 没有显式开启事务的读是快照,不会加锁

  3. 显式开启事务的读会加共享锁,类似于select ... lock in share mode,此时读写互斥。

 

 

测试环境:mysql 5.7.26,引擎InnoDB

 

 参考:https://blog.csdn.net/cuiyandan4490/article/details/100464470

posted @ 2021-03-25 13:46  walker993  阅读(68)  评论(0编辑  收藏  举报