2

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
1
  • u need "with" context manager Commented Mar 11, 2015 at 13:03

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.