python - 如果 MySQL 数据库连接池在很长一段时间内未使用或使用它的应用程序崩溃,它是否会过期?
问题描述
我正在使用 Python 脚本连接数据库 MySQL (MariaDB) MySQLConnectionPool
。我使用上下文管理器来处理池中的连接。我想知道如果长时间不使用或者我的程序崩溃了,池是否会过期。我发现与MySQL db的连接过期了,即使您忘记或无法关闭程序中的连接,它是否会被释放,连接池是什么情况?
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()
解决方案
是的,它可以超时。有两种超时配置。
推荐阅读
- python - 使用真实账户连接 XTB API 时出错
- mysql - myPhpAdmin,如何创建一个触发器,当有人更新一行中的任何列时,它将在特定列中添加一个“1”
- angular - 将 AD B2C 和 MSAL v2 与 Angular 结合使用,允许选择性的不受保护的 Web API 调用
- graph - 找出两个节点之间是否有边的时间复杂度
- c# - 使用三元条件运算符选择函数
- android - 如何使用原生 android 的标签栏加载 React Native Activity?
- c++ - 创建日期结构
- python - 如何在异步函数 discord.py 中添加空格
- prolog - 使用回溯解决 8 个难题的 prolog 代码:
- android - react-native android 原生 ui