資料庫隔離級別

2021-09-28 15:52:32 字數 2025 閱讀 2579

一、隔離級別的種類與分別可以解決的問題:

事務的隔離級別分為4個,即 讀未提交(read uncommitted)、讀已提交(read committed)、可重複讀(repeatable read)、可序列化(serializable)

oracle預設的隔離級別為 讀已提交。mysql的預設隔離級別為 可重複讀。

簡單來說:

髒讀即為session a讀取到了session b中未提交的資料

不可重複讀即為session a讀取到了session b提交的資料,即前後session a讀取的資料不一致

幻讀即為session a讀取到了session b insert的資料。

二、隔離級別的設定與查詢:

1、設定隔離級別:

設定隔離級別分為設定全域性的隔離級別與設定當前的隔離級別

全域性設定,已存在的session不會生效,以後的新session會生效(以讀未提交舉例):

set global transaction isolation level read uncommitted;

單獨設定當前連線:

set session transaction isolation level read uncommitted;

2 、檢視當前隔離級別:

select @tx_isolation;

三、事務隔離級別的測試:

有乙個goods表,裡面有id、count(商品數量)、brandid(品牌id)

create table `goods` (

`id` int(11) not null auto_increment,

`count` int(11) default '0',

`brandid` int(11) default '0',

primary key (`id`),

key `idx_brandid` (`brandid`)

) engine=innodb auto_increment=1 default charset=utf-8;

1、髒讀(設定隔離級別為讀未提交):

髒讀為讀到其它事務未提交的資料:ab

select * from goods where id = 1;

返回1update goods set count = 2 where id = 1;

select * from goods where id = 1;

返回2commit;

2、不可重複讀(設定隔離級別為 讀已提交)

不可重複讀為讀到其它資料已提交的資料,即前後查詢資料不一致

a  b

select * from goods where id = 1;

返回1update goods set count = 2 where id = 1;

select * from goods where id = 1;

返回1commit

select * from goods where id = 1;返回2

3、幻讀(設定隔離級別為 可重複讀):

幻讀為讀到別人已提交的寫入資料庫的資料。

幻讀與不可重複讀的區別為幻讀為讀到新插入的資料(insert),而不可重複讀主要是更改與刪除(update、delete)。

即不可重複讀前後被其它session update、delete的資料沒有問題,不會有變化,但是其它session insert的可能有變化。ab

select * from goods where brandid = 1;

返回有id為1,2的兩條

insert into goods (count,brandid) values (3, 1);

commit;

select * from goods where brandid = 1;

返回有id為1,2,3的三條

當隔離級別為 可序列化 的時候則不會出現上述問題。

資料庫隔離級別

read uncommited 讀未提交 最低級別,可讀取未提交事物的資料,這會導致髒讀,比如 某時刻會話a修改了乙個資料,但還未提交,此時會話b,讀取了該資料,這是,會話a回滾了事物,這就導致資料出現了不一致狀態,這就是髒讀 read commited 提交讀 避免了髒讀,但會導致不可重複讀,例如...

資料庫隔離級別

資料庫事務的隔離級別有4個,由低到高依次為read uncommitted read committed repeatable read serializable,這四個級別可以逐個解決髒讀 不可重複讀 幻讀這幾類問題。可能出現 不會出現 髒讀 不可重複讀 幻讀read uncommitted re...

資料庫隔離級別

資料庫事務的隔離級別有4個,由低到高依次為read uncommitted read committed repeatable read serializable,這四個級別可以逐個解決髒讀 不可重複讀 幻讀這幾類問題。可能出現 不會出現 髒讀不可重複讀 幻讀read uncommitted rea...