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

本地连接PythonAnywhere MySQL创建表时报2013连接丢失错误求助

问题原因

你的代码逻辑顺序错误:SSH隧道的with代码块结束后会自动关闭隧道连接,而你将MySQL查询操作放在了隧道块之外,此时隧道已经断开,依赖隧道传输的MySQL连接自然失效,因此触发2013连接丢失报错。

修复代码

import MySQLdb
import sshtunnel

sshtunnel.SSH_TIMEOUT = 15
sshtunnel.TUNNEL_TIMEOUT = 15
with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='MyUSERNAME', ssh_password='***',
    remote_bind_address=('MyUSERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    connection = MySQLdb.connect(
        user='MyUSERNAME',
        passwd='***',
        host='127.0.0.1', port=tunnel.local_bind_port,
        db='MyUSERNAME$liveSports',
    )
    # 所有数据库操作必须放在隧道with块内部
    cur = connection.cursor()
    with connection:
        cur.execute("CREATE TABLE table_one (date TEXT, start_time TEXT)")
    # 可选:验证建表结果
    # cur.execute("SHOW TABLES")
    # print(cur.fetchall())

其他排查点

  • 免费版PythonAnywhere账号需先在后台开启外部SSH访问权限,否则无法建立隧道连接。
  • 确认你的MySQL用户名、数据库名拼写和PythonAnywhere后台显示完全一致,数据库名强制为用户名$自定义库名格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:06:03