You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pythonanywhere无时间延迟仍出现MySQL连接错误问题咨询

核心错误原因

你的SSH隧道生命周期管理错误:SSHTunnelForwarder的with上下文块结束后,SSH隧道会自动销毁关闭。你把执行SQL的游标创建、循环插入逻辑全部放在了with块外部,此时隧道已经断开,依赖隧道的数据库连接自然失效,触发连接丢失报错。

修正后的代码

import MySQLdb, sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

queryAdd = ("INSERT INTO `****$geo***`.O***"
               "(name, address) "
               "VALUES (%s, %s)")

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='*******', ssh_password='*******',
    remote_bind_address=('*****.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    connection = MySQLdb.connect(
        user='******',
        passwd='********',
        host='127.0.0.1', port=tunnel.local_bind_port,
        db='****$geo******',
        )
    # 所有数据库操作都要放在with块内部,保证隧道存活
    cursor = connection.cursor()    

    for row in dl:
        tup=(row['name'],row['address'])
        cursor.execute(queryAdd, tup)
    # 批量操作完成后再统一提交,不需要每次循环提交,提升性能
    connection.commit()
    # 用完主动关闭连接
    connection.close()

其他可排查点

  • 确认配置项正确性:Pythonanywhere的MySQL主机地址、数据库用户名、数据库名(必须为你的Pythonanywhere用户名$实际库名格式)、密码等参数填写正确
  • 可适当调高超时参数测试:将SSH_TIMEOUT、TUNNEL_TIMEOUT调整为30,排除本地网络波动导致的短连接断开
  • 检查本地网络限制:确认本地防火墙、代理没有拦截到ssh.pythonanywhere.com的22端口SSH连接

内容的提问来源于stack exchange,提问作者chhibbz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:45:02