我正在使用從Python腳本連接數據庫MySQL(MariaDB)。我使用上下文管理器來連接池中的連接。我想知道如果長時間不使用或我的程序崩潰,池是否會過期。我發現與MySQL數據庫的連接過期,即使您忘記或無法在程序中關閉連接,它也會被釋放嗎,連接池的情況如何?MySQLConnectionPoolfrom contextlib import contextmanagerimport mysql.connectorfrom mysql.connector.errors import Errorfrom mysql.connector import poolingSQL_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)@contextmanagerdef 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()@contextmanagerdef mysql_curs_from_pool() -> "curs": with mysql_connection_from_pool() as _conn: _curs = _conn.cursor() try: yield _curs finally: _curs.close()
添加回答
舉報
0/150
提交
取消