即使没有时间延迟,Pythonanywhere 也会出现 MySQL 连接错误

Pythonanywhere giving MySQL connection error even without time delay

我正在尝试使用以下代码从本地 python 文件连接到我的 pythonanywhere 数据库。

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******',
        )

cursor = connection.cursor()    

for row in dl:
    tup=(row['name'],row['address'])
    cursor.execute(queryAdd, tup)
    connection.commit()

但是,一旦代码为 运行,我就会收到以下错误:

MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')

创建连接和运行执行查询之间没有延迟。我做错了什么?

你需要在你的 with 块内做所有事情,因为当你离开上下文时隧道就消失了。