简体   繁体   中英

psycopg2 pool SimpleConnectionPool needs commit?

I implemented this code to create a pool connection:

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)

And I do the select like this:

with getcursor() as cur:
    cur.execute("SELECT * FROM %s;" % (table))

My question is, does the connection and execute need the commit (the line commented out in create_global_connection)?

Here's a link to the psycopg2 documentation on transactions:

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

Quoting from the docs:

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

As written, your code will perform the select, but the cursor will close unless you use it inside the with block. The with construct is only available for version 2.5 or later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM