2009-08-02 52 views
18

Im擺弄psycopg2,雖然有一個.commit()和.rollback()沒有.begin()或類似的開始一個事務,或者它似乎? 我希望能夠做到如何使用psycopg2/python db api執行數據庫事務?

db.begin() # possible even set the isolation level here 
curs = db.cursor() 
cursor.execute('select etc... for update') 
... 
cursor.execute('update ... etc.') 
db.commit(); 

那麼,如何交易與psycopg2工作? 我將如何設置/更改隔離級別?

回答

23

使用db.set_isolation_level(n),假設db是您的連接對象。隨着費德里科寫道:heren的含義是:

0 -> autocommit 
1 -> read committed 
2 -> serialized (but not officially supported by pg) 
3 -> serialized 

如記錄herepsycopg2.extensions爲您提供的通用符號常量:

Setting transaction isolation levels 
==================================== 

psycopg2 connection objects hold informations about the PostgreSQL `transaction 
isolation level`_. The current transaction level can be read from the 
`.isolation_level` attribute. The default isolation level is ``READ 
COMMITTED``. A different isolation level con be set through the 
`.set_isolation_level()` method. The level can be set to one of the following 
constants, defined in `psycopg2.extensions`: 

`ISOLATION_LEVEL_AUTOCOMMIT` 
    No transaction is started when command are issued and no 
    `.commit()`/`.rollback()` is required. Some PostgreSQL command such as 
    ``CREATE DATABASE`` can't run into a transaction: to run such command use 
    `.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)`. 

`ISOLATION_LEVEL_READ_COMMITTED` 
    This is the default value. A new transaction is started at the first 
    `.execute()` command on a cursor and at each new `.execute()` after a 
    `.commit()` or a `.rollback()`. The transaction runs in the PostgreSQL 
    ``READ COMMITTED`` isolation level. 

`ISOLATION_LEVEL_SERIALIZABLE` 
    Transactions are run at a ``SERIALIZABLE`` isolation level. 


.. _transaction isolation level: 
    http://www.postgresql.org/docs/8.1/static/transaction-iso.html 
+0

不錯。它是否默認爲自動提交?當設置n = 1,2或3時開始一個事務?創建一個新的遊標,或者是自上次提交/回滾以來對數據庫的每個操作? – Leeeroy 2009-08-02 17:54:24

+0

Autocommit是大多數DBMS的默認設置。 – 2009-08-02 17:57:55

+1

亞歷克斯問我後增加了更多的東西。它表示READ_COMMITED是psycopg2的默認值 – Leeeroy 2009-08-02 18:04:02

5

我更明確地看到我的交易是:

  • cursor.execute(「BEGIN」)
  • cursor .execute(「COMMIT」)
12

帶有Python標準DB API的BEGIN始終是隱含的。當您開始使用數據庫時,驅動程序發出BEGIN,並且在任何COMMITROLLBACK之後發出另一個BEGIN。符合規範的Python DB API應該總是以這種方式工作(不僅僅是postgresql)。

您可以將此設置的隔離級別更改爲自動提交,如Alex Martelli指出的db.set_isolation_level(n)

正如Tebas所說,開始是隱式的,但在執行SQL之前不會執行,所以如果不執行任何SQL,則會話不在事務中。

相關問題