psycopg2池SimpleConnectionPool需要提交吗?

2024-05-18 07:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我实现此代码以创建池连接:

def create_global_connection(minconn, maxconn, _pgconnstr):
    global g_connection
    g_connection = psycopg2.pool.SimpleConnectionPool(minconn, maxconn, _pgconnstr)
    # global_connection.autocommit = True

@contextmanager
def getcursor():
    global g_connection
    conn = g_connection.getconn()
    try:
        yield conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    finally:
        g_connection.putconn(conn)

我这样做选择:

^{pr2}$

我的问题是,connection和execute是否需要提交(create_global_connection中注释掉的行)?在


Tags: 代码truedefcreateconnectionconnglobalcursor
1条回答
网友
1楼 · 发布于 2024-05-18 07:54:22

以下是有关事务的psycopg2文档的链接:

http://initd.org/psycopg/docs/usage.html#transactions-control

引用文件:

When a connection exits the with block, if no exception has been raised by the block, the transaction is committed. In case of exception the transaction is rolled back.

When a cursor exits the with block it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected.

Note that, unlike file objects or other resources, exiting the connection’s with block doesn’t close the connection but only the transaction associated with it: a connection can be used in more than a with statement and each with block is effectively wrapped in a separate transaction

如前所述,您的代码将执行select,但光标将关闭,除非您在with块中使用它。with构造仅适用于2.5版或更高版本。在

相关问题 更多 >