postgresql事務


查看更多教程:http://www.gitbook.net/postgresql/2013080567.html

 

pgsql事務與並發控制

事務與並發控制

數據庫幾大特性:

ACID

Atomicity:原子性:一個事務要么全部執行,要么全部不執行

Consistency :一致性:執行事務的時候,數據庫從一個一致的狀態變更到另一個狀態

 Isolation:隔離性: 確保在並發執行的時候,每個事務感覺不到其他事務在並發的執行

 Durability:持久性:一個事務完成之后,即使數據庫發生故障,他對數據庫的改變應該永久的保存在數據庫中。

 

並發引起的現象

  • 臟讀:一個事務讀取了第二個事務的已經修改但是未提交的數據
  • 不可重復讀:一個事務第一次讀取數據之后,被讀取的數據被另一個已提交的事務進行了修改,事務再次讀取這些數據時候發現數據已經被另外一個事務所修改,兩次查詢不一致
  • 幻讀:一個事務的兩次結果集記錄數不一致(特殊的不可重復讀)
  1. 查看數據庫的隔離級別操作
  • 查看全局事務級別
    select name,setting from pg_settings where name = 'default_transaction_isolation'
  • 修改全局事務隔離級別
    alter system set default_transaction_islation to 'REPEATABLE READ';select pg_reload_conf();select current_setting('transaction_isolation');
  • 查看當前會話的事務隔離級別
    show transaction_isolcation;
  • 設置當前事務的事務隔離級別
    start transaction isolation level READ UNCOMMITED;
  • start TRANSACTION    select xxxx
  • END

 

 

事物是如何開始的?

1、每條SQL語句就是一個事物。「自動提交模式」

2、直到用戶執行commit或rollback為止作一個事務。

 

2.1、事務開始 sql server 、Postgresql 是下面方式:

 

Begin transaction ;      

      Update student set name=‘teddy’ where id=3 ;

 

     Update student set age=‘13’ where id=3 ;

Commit ;———>提交處理

 

 

2.2、事務開始 mysql 是下面方式:start  transaction ;     

start transaction ;      

      Update student set name=‘teddy’ where id=3 ;

 

     Update student set age=‘13’ where id=3 ;

Commit ;———>提交處理

 

 

事務回滾例子:

begin transaction ;

      Update student set name=‘teddy’ where id=3 ;

 

     Update student set age=‘13’ where id=3 ;

rollback ;———>取消處理

 

 

 

創建表:create table student ( student_id integer , name varchar(12),sex varchar(12),age integer);

 

插入數據:insert into student values(1,'teddy','man',25),(2,’Tony’,’man',27)(3,’lida’,’man',25);

 

更新數據:Update student set name=‘teddy’ where id=3 ;

 

查詢:select*from student;

 

刪除數據: delete from student where student_id=1;  —————>  只刪除數據,表還存在。

 

刪除表:drop table student;——————————————>表和數據都刪除了。

 

刪除視圖:drop view aa_view_test;

 

創建視圖:create or replace view 

aa_view_test          ——>視圖名

 (name  , age)          ——>視圖里的字段

as 

select name ,age from student;

 

 

 

EXIST OR  NOT EXIST:是否存在

 

select name ,age from  student_a as A

where exist (select *from student_b. as B);

 

case用法:

 

case  type 

when ‘a’ then ‘一級’

when ‘b’ then ‘二級’

when ‘c’ then ‘三級’

else ‘其他’ end  as  類型

 

 

 

對集合的操作:

Union all  全部數據加起來「包含重復」

 

select *from student1

union all

select *from student2;

 

 

Intersect-----選取公共部分

select *from student1

Intersect

select *from student2;

 

 

except 記錄減法

select *from student1

except

select *from student2;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM