MySQL Connector循环执行时断开连接的原因排查
问题排查与解决方案
1. 修复SQL执行的参数传递错误
你的代码里cursor.execute()的调用方式存在明显错误:
query = ("SELECT * FROM search WHERE time= %s;", (date,)) cursor.execute(query)
这里你把SQL语句和参数打包成一个元组传给execute(),但execute()的正确用法是第一个参数为不带分号的SQL字符串,第二个参数为参数元组。错误的传递方式会触发执行逻辑异常,进而可能引发连接报错。
修正后的写法:
cursor.execute("SELECT * FROM search WHERE time= %s", (date,))
2. 解决MySQL连接超时问题
出现2055: Lost connection错误,核心原因是MySQL服务器的连接超时机制:
- MySQL默认的
wait_timeout和interactive_timeout通常为8小时,若循环执行时间过长、中间有长时间停顿,服务器会主动断开闲置连接; - 若单次查询耗时极长,也可能触发连接超时。
对应解决办法:
- 循环内自动检查并重连:
在每次循环前调用conn.ping(reconnect=True),自动检查连接状态,断开时会重新建立连接:for date in listdates: print(date) try: conn.ping(reconnect=True) cursor.execute("SELECT * FROM search WHERE time= %s", (date,)) row = cursor.fetchall() if not row: index = listdates.index(date) break except Exception: traceback.print_exc() print("did not return row") - 调整服务器超时配置:
若允许修改MySQL配置,可在my.cnf(Windows为my.ini)中延长超时时间,修改后重启服务:wait_timeout = 86400 interactive_timeout = 86400
3. 完善错误处理与资源释放
原代码存在资源泄漏和未定义变量风险:初始连接失败时cursor未定义,循环调用会触发新错误;循环结束后未关闭连接和游标。
优化后的完整代码示例:
import mysql.connector import traceback conn = None cursor = None index = 0 try: conn = mysql.connector.connect( user='root', password='####', host='####', database='###', allow_local_infile=True ) cursor = conn.cursor() except Exception: traceback.print_exc() print("I am unable to connect to the database") exit() try: for date in listdates: print(date) try: conn.ping(reconnect=True) cursor.execute("SELECT * FROM search WHERE time= %s", (date,)) row = cursor.fetchall() if not row: index = listdates.index(date) break except Exception: traceback.print_exc() print("did not return row") finally: # 确保资源被正确释放 if cursor: cursor.close() if conn: conn.close()
4. 其他排查方向
- 检查网络稳定性:远程连接时,网络波动可能导致连接断开;
- 查看MySQL服务器日志:通过
error.log确认是否存在服务器端异常(比如资源不足、连接数耗尽)。
内容的提问来源于stack exchange,提问作者tab_philomath
相关产品推荐
相关产品推荐

