Ma Tingchen
Ma Tingchen

Reputation: 171

How to ensure the MySQL connection is returned to connection pool with MySQL Python Connector?

I'm using the official python MySQL connector and I want to use its connection pool to manage the connections. The question is, if I get a connection from the pool, an uncaught exception is thrown before the connection is returned to the pool or I just forget to close it, will the pool close the connection automatically? If not, how can I make sure that the connection can be returned to the pool under any circumstances?

For example:

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

Upvotes: 2

Views: 1821

Answers (1)

Kaz
Kaz

Reputation: 816

You can use contextlib.closing() as follows.

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

Upvotes: 1

Related Questions