我在摆弄 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
是您的连接对象。正如费德里科所写 here ,n
的意思是:
0 -> autocommit
1 -> read committed
2 -> serialized (but not officially supported by pg)
3 -> serialized
据记录 here , 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 - 如何使用 psycopg2/python db api 进行数据库事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1219326/