首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用python copg2/python db api进行数据库事务处理?

如何使用python copg2/python db api进行数据库事务处理?
EN

Stack Overflow用户
提问于 2009-08-02 17:26:17
回答 2查看 31.7K关注 0票数 25

我正在摆弄psycopg2,虽然有.commit()和.rollback(),但没有.begin()或类似的启动事务,或者看起来是这样?我希望能够做到

代码语言:javascript
复制
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协同工作呢?如何设置/更改隔离级别?

EN

回答 2

Stack Overflow用户

发布于 2009-08-02 17:47:19

假设db是您的连接对象,请使用db.set_isolation_level(n)。正如费德里科所写的heren的含义是:

代码语言:javascript
复制
0 -> autocommit
1 -> read committed
2 -> serialized (but not officially supported by pg)
3 -> serialized

正如here文档所述,psycopg2.extensions为您提供了符号常量:

代码语言:javascript
复制
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
票数 31
EN

Stack Overflow用户

发布于 2009-08-12 11:03:28

带有python标准DB的BEGIN总是隐式的。当您开始使用数据库时,驱动程序会发出一个BEGIN,在任何COMMITROLLBACK之后,都会发出另一个BEGIN。符合规范的python DB API应该始终以这种方式工作(不仅仅是postgresql)。

您可以将此设置更改为使用db.set_isolation_level(n)自动提交隔离级别,正如Alex Martelli所指出的那样。

正如Tebas所说,begin是隐式的,但在执行SQL之前不会执行,因此如果您不执行任何SQL,则会话不在事务中。

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1219326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档