PostgreSQL设置事务隔离级别实验

apple=# begin;
BEGIN
apple=# set transaction ISOLATION LEVEL read committed ;
SET
apple=# select * from test;
 id | info
----+-------
  2 | test
  3 | test1
  4 | test1
  5 | test
  6 | test
  7 | test
  8 | test1
  9 | test1
 10 | test
 11 | test
  1 | test
  1 | test
  1 | test
  1 | test
  1 | test
(15 rows)

中间别的连接插入一条数据,并提交,在本事务内查询,多了一条。
apple=# select * from test; id | info ----+------- 2 | test 3 | test1 4 | test1 5 | test 6 | test 7 | test 8 | test1 9 | test1 10 | test 11 | test 1 | test 1 | test 1 | test 1 | test 1 | test 1 | test (16 rows) apple=# commit; COMMIT

设置隔离级别为可重复读:
apple=# begin; BEGIN apple=# set transaction ISOLATION LEVEL repeatable READ; SET apple=# select * from test; id | info ----+------- 2 | test 3 | test1 4 | test1 5 | test 6 | test 7 | test 8 | test1 9 | test1 10 | test 11 | test 1 | test 1 | test 1 | test 1 | test 1 | test 1 | test (16 rows)
中间别的连接插入一条数据,并查询:
apple=# select * from test; id | info ----+------- 2 | test 3 | test1 4 | test1 5 | test 6 | test 7 | test 8 | test1 9 | test1 10 | test 11 | test 1 | test 1 | test 1 | test 1 | test 1 | test 1 | test (16 rows) apple=#

设置隔离级别只能在事物段中执行:

apple=# set transaction ISOLATION LEVEL repeatable READ;
WARNING:  SET TRANSACTION can only be used in transaction blocks
SET

在PG配置文件有一项配置提交级别:

#default_transaction_isolation = 'read committed'

Read committed(读已提交)

读已提交是PostgreSQL中的默认隔离级别。 当一个事务运行使用这个隔离级别时, 一个查询(没有FOR UPDATE/SHARE子句)只能看到查询开始之前已经被提交的数据, 而无法看到未提交的数据或在查询执行期间其它事务提交的数据。实际上,SELECT查询看到的是一个在查询开始运行的瞬间该数据库的一个快照。不过SELECT可以看见在它自身事务中之前执行的更新的效果,即使它们还没有被提交。

所以脏读现象将不会再发生。

还要注意的是,即使在同一个事务里两个相邻的SELECT命令可能看到不同的数据,因为其它事务可能会在第一个SELECT开始和第二个SELECT开始之间提交。即会造成不可重复读。

Repeatable read(可重复读)

可重复读隔离级别只看到在事务开始之前被提交的数据;它从来看不到未提交的数据或者并行事务在本事务执行期间提交的修改(不过,查询能够看见在它的事务中之前执行的更新,即使它们还没有被提交)。

这个级别与读已提交不同之处在于,一个可重复读事务中的查询可以看见在事务中第一个非事务控制语句开始时的一个快照,而不是事务中当前语句开始时的快照。因此,在一个单一事务中的后续SELECT命令看到的是相同的数据,即它们看不到其他事务在本事务启动后提交的修改。

猜你喜欢

转载自www.cnblogs.com/kuang17/p/10065002.html