Home > Database > Mysql Tutorial > body text

MySQL InnoDB存储引擎的事务隔离级别_MySQL

WBOY
Release: 2016-06-01 14:01:24
Original
860 people have browsed it

我们知道,在关系数据库标准中有四个事务隔离级别:

  未提交读(Read Uncommitted):允许脏读,也就是可能读取到其他会话中未提交事务修改的数据

  提交读(Read Committed):只能读取到已经提交的数据。Oracle等多数数据库默认都是该级别

  可重复读(Repeated Read):可重复读。在同一个事务内的查询都是事务开始时刻一致的,InnoDB默认级别。在SQL标准中,该隔离级别消除了不可重复读,但是还存在幻象读

  串行读(Serializable):完全串行化的读,每次读都需要获得表级共享锁,读写相互都会阻塞

  查看InnoDB系统级别的事务隔离级别:

mysql> SELECT @@global.tx_isolation;
+-----------------------+
| @@global.tx_isolation |
+-----------------------+
| REPEATABLE-READ   |
+-----------------------+
1 row in set (0.00 sec)

  查看InnoDB会话级别的事务隔离级别:

mysql> SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set (0.00 sec)

  修改事务隔离级别:

  mysql> set global transaction isolation level read committed;

  Query OK, 0 rows affected (0.00 sec)

  mysql> set session transaction isolation level read committed;

  Query OK, 0 rows affected (0.00 sec)

  InnoDB的可重复读隔离级别和其他数据库的可重复读是有区别的,不会造成幻象读(phantom read),所谓幻象读,就是同一个事务内,多次select,可以读取到其他session insert并已经commit的数据。下面是一个小的测试,证明InnoDB的可重复读隔离级别不会造成幻象读。测试涉及两个session,分别为session 1和session 2,隔离级别都是repeateable read,关闭autocommit

mysql> select @@tx_isolation;
+-----------------+
| @@tx_isolation |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set (0.00 sec)

  mysql> set autocommit=off;

  Query OK, 0 rows affected (0.00 sec)

  session 1 创建表并插入测试数据

  mysql> create table test(i int) engine=innodb;

  Query OK, 0 rows affected (0.00 sec)

  mysql> insert into test values(1);

  Query OK, 1 row affected (0.00 sec)

  session 2 查询,没有数据,正常,session1没有提交,不允许脏读

  mysql> select * from test;

  Empty set (0.00 sec)

  session 1 提交事务

  mysql> commit;

  Query OK, 0 rows affected (0.00 sec)

  session 2 查询,还是没有数据,没有产生幻象读

  mysql> select * from test;

  Empty set (0.00 sec)

  以上试验版本:

mysql> select version();
+-------------------------+
| version()       |
+-------------------------+
| 5.0.37-community-nt-log |
+-------------------------+
1 row in set (0.00 sec)

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template