首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何确保使用MySQL Python Connector将MySQL连接返回到连接池?

问如何确保使用MySQL Python Connector将MySQL连接返回到连接池?
EN

Stack Overflow用户
提问于 2015-03-11 19:51:10
回答 1查看 995关注 0票数 2

我使用的是官方的python MySQL连接器,我想使用它的连接池来管理连接。问题是,如果我从池中获得一个连接,在连接返回到池之前抛出一个未捕获的异常,或者我只是忘记关闭它,池会自动关闭连接吗?如果没有,我如何确保连接在任何情况下都可以返回到池中?

例如:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2019-10-03 07:56:55

您可以使用contextlib.closing(),如下所示。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28985904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档