我正在摆弄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协同工作呢?如何设置/更改隔离级别?
发布于 2009-08-02 17:47:19
假设db
是您的连接对象,请使用db.set_isolation_level(n)
。正如费德里科所写的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
发布于 2009-08-12 11:03:28
带有python标准DB的BEGIN
总是隐式的。当您开始使用数据库时,驱动程序会发出一个BEGIN
,在任何COMMIT
或ROLLBACK
之后,都会发出另一个BEGIN
。符合规范的python DB API应该始终以这种方式工作(不仅仅是postgresql)。
您可以将此设置更改为使用db.set_isolation_level(n)
自动提交隔离级别,正如Alex Martelli所指出的那样。
正如Tebas所说,begin是隐式的,但在执行SQL之前不会执行,因此如果您不执行任何SQL,则会话不在事务中。
https://stackoverflow.com/questions/1219326
复制相似问题