MySQL事務

事務特性ACID

1. Atomicity(原子性)
2. Consistency(一致性)
3. Isolation(隔離性)
4. Durability(持久性)
  • 查看事務隔離級別
    select @@tx_isolation;
  • 開始關閉事務
//開始事務
start transaction/begin;

//提交或回滾
commit/rollback
  • 設置事務自動提交開關
    SET autocommit = {0 | 1}
  • 設置事務隔離級別
SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL READ COMMITTED

可選的事務隔離級別有:
REPEATABLE READ
READ COMMITTED
READ UNCOMMITTED
SERIALIZABLE

數據庫併發問題

  • 讀髒
    事務T1讀取了事務T2未提交的更新後的數據。
  • 不可重複讀
    事務T1執行過程中,事務T2提交了新數據,事務T1在事務T2提交前後讀到的數據不一致。
  • 幻讀
    事務T1的插入或刪除(事務已提交)導致事務T2在行數上不一致的情況。

    MySQL各事務隔離級別對併發問題的解決

事務隔離級別 讀髒 不可重複讀 幻讀
讀未提交(Read-Uncommitted) 可能 可能 可能
讀提交(Read-Committed) 不可能 可能 可能
可重複讀(Repeatable-Read) 不可能 不可能 可能
串行化(Serializable) 不可能 不可能 不可能
下面兩個例子說明RR下是有幻讀現象的
create table goods(
id int primary key,
name varchar(100),
amount int not null
);
  1. 插入幻讀
事務1 事務2
begin; begin;
select * from goods;
Empty set (0.00 sec)
insert into goods(id, name, amount) values(1, '蘋果', 100);
commit;
insert into goods(id, name, amount) values(1, '蘋果', 100);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

對於事務1,開始表爲空的,後來插入是重複的key,幻覺出現。

  1. 更新幻讀
事務1 事務2
begin; begin;
select * from goods;
1 row in set (0.00 sec)
insert into goods(id, name, amount) values(2, '香蕉', 100);
commit;
update goods set amount=1;
Rows matched: 2 Changed: 2 Warnings: 0

對於事務1,開始查詢表有一條記錄,後來更新卻發現有兩條數據被更新了,幻覺出現。

共享鎖與排他鎖

共享鎖(shared (S) lock)
A kind of lock that allows other transactions to read the locked object, and to also acquire other shared locks on
it, but not to write to it.  
共享鎖又叫S鎖,一個事務對資源加共享鎖,那麼其他事務還可以對此資源加共享鎖,但是不能加排他鎖。也即是說對資源加共享鎖意味着資源可以被讀但是不能對其進行刪除和修改。如果事務T1對某一資源加共享鎖,在沒有其他事務對此資源加共享鎖的情況下那麼T1還可以對此資源加排它鎖。  

使用語法:
begin;
select * from tableName where id=2 lock in share mode;
commit;
排他鎖(exclusive (X) lock )
A kind of lock that prevents any other transaction from locking the same row. Depending on the transaction
isolation level, this kind of lock might block other transactions from writing to the same row, or might also block
other transactions from reading the same row. The default InnoDB isolation level, REPEATABLE READ, enables
higher concurrency by allowing transactions to read rows that have exclusive locks, a technique known as
consistent read.  
排他鎖又叫X鎖,在事務中刪除、更新以及插入都會對資源加排它鎖,對資源加排它鎖後就不能對其加共享鎖和排它鎖了。如果再加則會引起阻塞直到上一個鎖釋放。

使用語法:
begin;
select * from tableName where id=2 for update;
commit;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章