A
A
ArtiomK2020-03-02 10:57:26
MySQL
ArtiomK, 2020-03-02 10:57:26

How to properly close a MySQL Python Connection Pool?

I'm using a Connection Pool in a Flask app so that there are multiple connections that are picked up and returned to the Pool as needed without closing the connection after being used in a query. Implemented this through the context manager:

from contextlib import contextmanager
import mysql.connector
from mysql.connector.errors import Error
from mysql.connector import pooling

SQL_CONN_POOL = pooling.MySQLConnectionPool(
    pool_name="mysqlpool",
    pool_size=1,
    user=DB_USER,
    password=DB_PASS,
    host=DB_HOST,
    database=DATABASE,
    auth_plugin=DB_PLUGIN
)

@contextmanager
def mysql_connection_from_pool() -> "conn":
    conn_pool = SQL_CONN_POOL  # get connection from the pool, all the rest is the same
    _conn = conn_pool.get_connection()
    try:
        yield _conn
    except (Exception, Error) as ex:
        # if error happened all made changes during the connection will be rolled back:
        _conn.rollback()
        # this statement re-raise error to let it be handled in outer scope:
        raise
    else:
        # if everything is fine commit all changes to save them in db:
        _conn.commit()
    finally:
        # actually it returns connection to the pool, rather than close it
        _conn.close()


@contextmanager
def mysql_curs_from_pool() -> "curs":
    with mysql_connection_from_pool() as _conn:
        _curs = _conn.cursor()
        try:
            yield _curs
        finally:
            _curs.close()


I know that if DB connections are idle for a certain amount of time, then MySQL terminates them. The timing of this completion is determined by the global MySQL settings, which I do not have access to. Regarding Pool, I did not find a clear answer. Suppose I am debugging an application and close it periodically, when I force the application to close, what happens to the Pool connections? How does a Pool maintain its incoming connections if they are not used for a long time? How to terminate a Pool at the Python/Flask level?

Addendum: At the moment, I did not understand the advantages of SQL Alchemy, except for the ability to easily change the DB, for example, from MySQL to PostgreSQL, so I use the context manager and standard SQL queries.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question