如何确保MySQL连接通过MySQL Python连接器返回到连接池?
我使用的是官方的python MySQL连接器,我想使用它的连接池来管理连接。问题是,如果我从池中获取连接,在连接返回到池之前会抛出一个未捕获的异常,或者我只是忘记关闭它,那么池会自动关闭连接吗?如果没有,我如何确保在任何情况下都可以将连接返回到池 例如:如何确保MySQL连接通过MySQL Python连接器返回到连接池?,python,mysql,Python,Mysql,我使用的是官方的python MySQL连接器,我想使用它的连接池来管理连接。问题是,如果我从池中获取连接,在连接返回到池之前会抛出一个未捕获的异常,或者我只是忘记关闭它,那么池会自动关闭连接吗?如果没有,我如何确保在任何情况下都可以将连接返回到池 例如: import mysql.connector as mysql pool = mysql.pooling.MySQLConnectionPool(pool_name = "name", pool_size = 3, pool_reset_s
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
您可以使用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 automatically
你需要与上下文管理器