我使用官方的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
答案 0 :(得分:0)
您可以按如下方式使用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