我使用的是官方的python MySQL连接器,我想使用它的连接池来管理连接。问题是,如果我从池中获得一个连接,在连接返回到池之前抛出一个未捕获的异常,或者我只是忘记关闭它,池会自动关闭连接吗?如果没有,我如何确保连接在任何情况下都可以返回到池中?
例如:
import mysql.connector as mysql
pool = mysql.pooling.MySQLConnectionPool(pool_name = "name", pool_size = 3, pool_reset_session = True, **dbConfig)
for i in range(3):
cnx = pool.get_connection()
#if I forget to call cnx.close(), the pool will be exhausted
# now the pool is exhausted
cnx = pool.get_connection() #PoolError is raised发布于 2019-10-03 07:56:55
您可以使用contextlib.closing(),如下所示。
from contextlib import closing
.....
for i in range(3):
with closing(pool.get_connection()) as cnx:
# use cnx here
print cnx
# cnx.close() is called automaticallyhttps://stackoverflow.com/questions/28985904
复制相似问题