python - 如何使用 psycopg2/python db api 进行数据库事务?

标签 python database postgresql

我在摆弄 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 是您的连接对象。正如费德里科所写 heren的意思是:

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/

相关文章:

mysql - 有效地按类别进行组织

python - Heroku 导入错误 : No Module named hello

python - 如果其他属性为 != None,如何将类输出为嵌套字典并计算属性

MySQL db 消失了如何跟踪发生了什么?

java - Hibernate 选择和插入奇怪的行为

postgresql - 如何有效地将大型 PostGIS (PostgreSQL) 表导出到 GeoJSON 文件?

postgresql - Sequelize 不会创建外键作为约束

SQL 左连接获取匹配记录作为 true 或 false 列

python - 如何删除python3中的b符号

python - 安装模块 "Configobj 4.7.2"错误