如何确保MySQL连接通过MySQL Python Connector返回到连接池?

问题描述 投票:2回答:1

我使用的是官方的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
python mysql
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.