连接到 PythonAnywhere SQL 服务器的问题

Issues connecting to PythonAnywhere SQL Server

我正在尝试从我的本地计算机在 pythonAnywhere 上的 mySQL 服务器 运行 中创建一个 table。 我遵循了入门指南 https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere,但我 运行 遇到了 OperationalError: (2013, 'Lost connection to MySQL server during query').

这是我的代码:

import MySQLdb
import sshtunnel

sshtunnel.SSH_TIMEOUT = 10
sshtunnel.TUNNEL_TIMEOUT = 10
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',
    )



cur = connection.cursor()
with connection:
    cur.execute("CREATE TABLE table_one (date TEXT, start_time TEXT)")

我不确定为什么会收到此错误或如何解决它。 类似的错误 Lost connection to MySQL server during query 表明我向我的服务器发送了不正确的查询,但据我所知这是一个有效的查询,或者我的数据包太大,我不相信空 table 将是。

我是 SQL 的新手,但我似乎找不到这个问题的答案。

你必须让隧道保持畅通。这是简单的方法:

import MySQLdb
import sshtunnel

sshtunnel.SSH_TIMEOUT = 10
sshtunnel.TUNNEL_TIMEOUT = 10
tunnel = sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='MyUSERNAME', ssh_password='***',
    remote_bind_address=('MyUSERNAME.mysql.pythonanywhere-services.com', 3306)
)
connection = MySQLdb.connect(
    user='MyUSERNAME',
    passwd='***',
    host='127.0.0.1', port=tunnel.local_bind_port,
    db='MyUSERNAME$liveSports',
)

cur = connection.cursor()
cur.execute("CREATE TABLE table_one (date TEXT, start_time TEXT)")

您可以将所有数据库内容放入一个函数中并使用

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='MyUSERNAME', ssh_password='***',
    remote_bind_address=('MyUSERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    do_all_processing()

def do_all_processing():
    connection = MySQLdb.connect(
        user='MyUSERNAME',
        passwd='***',
        host='127.0.0.1', port=tunnel.local_bind_port,
        db='MyUSERNAME$liveSports',
    )
    ...etc...