事務(wù)隔離級別
my_id是主鍵
mysql> select * from mytable;
+-------------+------+------+-----------+-------+
| name? ? ? ? | sex? | age? | birthaddr | my_id |
+-------------+------+------+-----------+-------+
| xiaoming? ? | f? ? |? 20 | SZ? ? ? ? |? ? 1 |
| hello_world | m? ? |? 18 | BJ? ? ? ? |? ? 2 |
| world? ? ? | f? ? |? 21 | SZ? ? ? ? |? ? 3 |
| happy? ? ? | M? ? |? 99 | SH? ? ? ? |? ? 4 |
| happy1? ? ? | M? ? |? 99 | SH? ? ? ? |? ? 5 |
| happy2? ? ? | M? ? |? 99 | SH? ? ? ? |? ? 6 |
| happy3? ? ? | F? ? |? 18 | SH? ? ? ? |? ? 7 |
+-------------+------+------+-----------+-------+
7 rows in set (0.00 sec)
以下兩個事務(wù)的執(zhí)行結(jié)果绢要,可以得出
1饺律、Mysql的當(dāng)前級別是可重復(fù)讀Reapeatable Read(RR)关划,即事務(wù)1 讀取不到其他事務(wù)已提交的修改刹淌,通過MVCC來實(shí)現(xiàn)
2朗兵、Mysql的RR級別也實(shí)現(xiàn)了幻讀川梅,即事務(wù)1讀取不到其他事務(wù)已提交的新增
3列吼、事務(wù)之間的隔離是通過鎖來實(shí)現(xiàn)的
? 3.1 事務(wù)中的查詢和新增不需要鎖
? 3.2 事務(wù)中的修改:
? 對于索引列的修改岭洲,只需要鎖定修改的行(行鎖)沪编,所以只要不修改同一行是可以成功的
? 對于非索引列的修改呼盆,需要鎖整個表,所以會修改失敗
事務(wù)1 事務(wù)2
1.1-begin; ?
2.1-select * = 7 rows 2.2begin; ?
3.1update mytable set name="hello_world11" where my_id=2; 3.2select * = 7 rows ?
4.2update mytable set name="xiao" where my_id=1;更新成功??
5.2insert into mytable(name, sex, age, birthaddr) values ("happy66","F",18,"SH");插入成功??
6.2commit; ?
7.1select * = 7 rows
未讀取到my_id=1 name的更新,未讀取到happy66的數(shù)據(jù)插入
說明:
1 Mysql是可重復(fù)讀蚁廓,RR repeatable Read
2 并且實(shí)際上Mysql是解決了幻讀的 ?
8.2begin; ?
9.2update mytable set name="hello_world22" where my_id=2;更新失敗
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction ?
10.2update mytable set name="nihao_hello" where name="nihao";更新失敗
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction ?
11.1commit; ?
12.1select * = 8 rows
并且讀取到了my_id=1的更新访圃,即name=xiao ?
13.2再次執(zhí)行上面兩個更新,都可以成功 ?
13.3commit;
mysql> select * from mytable;
+---------------+------+------+-----------+-------+
| name? ? ? ? ? | sex? | age? | birthaddr | my_id |
+---------------+------+------+-----------+-------+
| xiao? ? ? ? ? | f? ? |? 20 | SZ? ? ? ? |? ? 1 |
| hello_world22 | m? ? |? 18 | BJ? ? ? ? |? ? 2 |
| world? ? ? ? | f? ? |? 21 | SZ? ? ? ? |? ? 3 |
| happy? ? ? ? | M? ? |? 99 | SH? ? ? ? |? ? 4 |
| happy1? ? ? ? | M? ? |? 99 | SH? ? ? ? |? ? 5 |
| happy2? ? ? ? | M? ? |? 99 | SH? ? ? ? |? ? 6 |
| happy3? ? ? ? | F? ? |? 18 | SH? ? ? ? |? ? 7 |
| happy55? ? ? | F? ? |? 18 | SH? ? ? ? |? ? 8 |
| happy66? ? ? | F? ? |? 18 | SH? ? ? ? |? ? 9 |
+---------------+------+------+-----------+-------+
9 rows in set (0.00 sec)