oracle之事務隔離級別
本文小節了oracle中事務隔離級別。
ANSI SQL標準定義了4中隔離級別:
READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE
隔離級別允許或不允許的3種現象
Dirty read(臟讀):能讀到未提交的數據。
Nonrepeatable read(不可重復讀):可能會出現丟失更新。
Phantom read(幻像讀): 已讀的數據不會改變,和以前相比,可能會有更多滿足條件的數據。
ANSI隔離級別
隔離級別 臟讀 不可重復讀 幻像讀
READ UNCOMMITTED 允許 允許 允許
READ COMMITTED 不允許 允許 允許
REPEATABLE READ 不允許 不允許 允許
SERIALIZABLE 不允許 不允許 不允許
以下部分測試例子。
1、READ UNCOMMITTED
允許臟讀,不可重復讀和幻像讀。這里想更改隔離級別,直接報錯。
SQL> SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
*
ERROR at line 1:
ORA-02179: valid options: ISOLATION LEVEL { SERIALIZABLE | READ COMMITTED }
2、READ COMMITTED
oracle的默認隔離選項。事務只能讀取數據庫中已經提交的數據。不允許臟讀。
session 1:
SQL> conn test/test
Connected.
SQL> SET TRANSACTION
2 ISOLATION LEVEL
3 READ COMMITTED;
Transaction set.
SQL> select * from t;
X
----------
1
session 2:
SQL> conn test/test
Connected.
SQL> SET TRANSACTION
2 ISOLATION LEVEL
3 READ COMMITTED;
Transaction set.
SQL> select * from t;
X
----------
1
session 1:
SQL> update t set x=2;
1 row updated.
SQL> insert into t values (3);
1 row created.
SQL> commit;
Commit complete.
SQL> select * from t;
X
----------
2
3
session 2:
SQL> select * from t;
X
----------
2
3
==>驗證了允許不可重復讀和幻象讀。
3、REPEATABLE READ
能給出一正確的結果,避免丟失更新。即不允許臟讀和重復讀,允許幻讀。
4、SERIALIZABLE
最高程度的隔離性。即不允許臟讀,不可重復讀和幻讀。
session 1;
SQL> select * from t;
X
----------
1
session2:
SQL> select * from t;
X
----------
1
SQL> SET TRANSACTION
2 ISOLATION LEVEL SERIALIZABLE;
Transaction set.
SQL> select * from t;
X
----------
1
session1:
SQL> insert into t values (2);
1 row created.
SQL> commit;
Commit complete.
SQL> select * from t;
X
----------
1
2
session 2:
SQL> select * from t;
X
----------
1
SQL> update t set x=2;
update t set x=2
*
ERROR at line 1:
ORA-08177: can't serialize access for this transaction
==》自事務后,session1又添加了一行為2記錄,session2更改報錯。
總結:
1.oracle只允許隔離級別更改為SERIALIZABLE和READ COMMITTED,默認為READ COMMITTED。
2.設置為最高級別的隔離選項(SERIALIZABLE)后,可能會在事務內遇到ORA-08177。
end;