psycopg2 池 SimpleConnectionPool 需要提交吗?
psycopg2 pool SimpleConnectionPool needs commit?
我实现了这段代码来创建池连接:
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)
我这样 select:
with getcursor() as cur:
cur.execute("SELECT * FROM %s;" % (table))
我的问题是,连接和执行是否需要提交(在 create_global_connection 中注释掉的行)?
这是关于交易的 psycopg2 文档的 link:
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 或更高版本。
我实现了这段代码来创建池连接:
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)
我这样 select:
with getcursor() as cur:
cur.execute("SELECT * FROM %s;" % (table))
我的问题是,连接和执行是否需要提交(在 create_global_connection 中注释掉的行)?
这是关于交易的 psycopg2 文档的 link:
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 或更高版本。