关闭twisted adbapi的自动提交(psycopg2)

2 投票
3 回答
2122 浏览
提问于 2025-04-17 13:50

我正在插入很多行数据,感觉PostgreSQL数据库跟不上了。我在网上查了一下,发现有人建议可以关闭自动提交功能。我并不需要立刻提交这些值,因为这些数据如果出问题我还可以再取回来。

但是当我搜索如何关闭自动提交时,找不到我想要的信息。我尝试在数据库连接池的构造函数里加上autocommit=False:

dbpool = adbapi.ConnectionPool('psycopg2', user="xxx", password="xxx", database="postgres", host="localhost", autocommit=False)

2013-01-27 18:24:42,254 - collector.EventLogItemController - 警告 - [失败实例:追踪信息:无效的连接选项 "autocommit"

3 个回答

0

使用 twisted.enterprise.adbapi.ConnectionPoolcp_openfun 选项来创建连接池,具体可以参考这个 文档

这个函数会接收一个连接作为参数。

如果你使用的是 psycopg2,你可以根据 这里的说明,将这个连接的自动提交属性设置为 TrueFalse

0

adbapi的问题在于:
1)它缺少一些数据库后端特有的功能。
2)它的异步接口其实是假的。实际上,它是在后台使用线程池来调用那些会阻塞的函数。

对于Postgres数据库,我建议使用txpostgres库(源代码在这里:https://github.com/wulczer/txpostgres)。这个库使用了psycopg2的异步接口,并且允许你指定连接字符串。
你可以在这里找到一个示例:http://txpostgres.readthedocs.org/en/latest/usage.html#customising-the-connection-and-cursor-factories

1

psycopg2并没有说它支持在connect里使用autocommit这个参数:

connect(dsn=None, database=None, user=None, password=None, host=None, port=None, connection_factory=None, async=False, **kwargs)
    Create a new database connection.

    The connection parameters can be specified either as a string:

        conn = psycopg2.connect("dbname=test user=postgres password=secret")

    or using a set of keyword arguments:

        conn = psycopg2.connect(database="test", user="postgres", password="secret")

    The basic connection parameters are:

    - *dbname*: the database name (only in dsn string)
    - *database*: the database name (only as keyword argument)
    - *user*: user name used to authenticate
    - *password*: password used to authenticate
    - *host*: database host address (defaults to UNIX socket if not provided)
    - *port*: connection port number (defaults to 5432 if not provided)

    Using the *connection_factory* parameter a different class or connections
    factory can be specified. It should be a callable object taking a dsn
    argument.

    Using *async*=True an asynchronous connection will be created.

    Any other keyword parameter will be passed to the underlying client
    library: the list of supported parameter depends on the library version.

而且现在的PostgreSQL文档里也没有提到什么“autocommit”参数:

http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING

所以可能问题在于,这不是关闭psycopg2连接的autocommit的正确方法。除此之外,你会发现关闭autocommit其实对你没有什么帮助。adbapi.ConnectionPool会为你开始和提交明确的事务,这样就绕过了autocommit模式可能带来的任何行为。

撰写回答