簡體   English   中英

如何使用 psycopg2/python db api 進行數據庫事務?

[英]How do I do database transactions with psycopg2/python db api?

我在擺弄 psycopg2 ,雖然有 .commit() 和 .rollback() ,但沒有 .begin() 或類似的東西來啟動事務,或者看起來是這樣? 我希望能夠做到

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 一起工作? 我將如何設置/更改隔離級別?

使用db.set_isolation_level(n) ,假設db是您的連接對象。 正如 Federico 在此處所寫, n的含義是:

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

如此處所述psycopg2.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

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

您可以將此設置隔離級別更改為使用db.set_isolation_level(n)自動提交, db.set_isolation_level(n) Alex Martelli 所指出的那樣。

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

我更喜歡明確地看到我的交易在哪里:

  • cursor.execute("BEGIN")
  • cursor.execute("COMMIT")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM