如何设置 Python 中的 SQL 查询超时?

直接说出计划。

PyMySQL超时设置: 蟒蛇 conn = pymysql.connect(host="localhost", user="user", password="password", db="database", read_timeout=1 0)
超时1 0秒,读取超时。

Django超时: 蟒蛇 数据库= { “默认”:{ '引擎': 'django.db.backends.mysql', '名称':'数据库', '用户':'用户', '密码': '密码', '主机':'本地主机', “选项”:{ '连接超时':1 0, }, }
连接超时 1 0 秒。

SQLAlchemy 超时: 蟒蛇 engine = create_engine('mysql+pymysql://user:password@localhost/database', connect_args={'connect_timeout': 1 0})
连接超时时间为 1 0 秒。

拦截异常: 蟒蛇 尝试: Cursor.execute("选择睡眠(1 0)") 除了操作错误为 e: print(f"查询失败:{e}")
UWSGI 超时: .ini [uwsgi] http=:8 000 模块=应用程序:应用程序 harakiri=6 0
请求超时 6 0 秒。

Gunicorn 超时: 巴什 Gunicorn --timeout 6 0 app:app
工作进程超时 6 0 秒。

记住:不同数据库中超时参数的名称可能不同。

Python脚本访问PolarDB数据库速度快却导致数据库卡死是什么原因?

数据库被封锁。
根本原因是连接没有关闭。

1 0年内,9 0%的类似问题都会发生在这里。

直接看日志,活跃连接数超过了最大连接数(例如PolarDB默认是1 00)。

不要相信setautocommit。
没关系。

这样做:使用 try-finally 来确保 close()。

监控连接计数并设置警报。