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

PyCharm无法连接PythonAnywhere MySQL数据库的问题求助

问题描述
  • 在PythonAnywhere付费账户上搭建了MySQL数据库和Web应用,在PythonAnywhere环境内运行正常,可正常连接并使用数据库中的数据。
  • 但在PyCharm中运行完全相同的代码时,无法访问数据库,报错信息如下:

Database connection failed: 2003 (HY000): Can't connect to MySQL server on '{my_user_name}.mysql.pythonanywhere-services.com:3306' (60)

  • 例外情况:PyCharm自带的数据库功能可以正常连接该MySQL数据库。
  • 数据库连接基础代码:
def get_db_connection():
    try:
        return mysql.connector.connect(
            host=os.getenv('DB_HOST'),
            user=os.getenv('DB_USER'),
            password=os.getenv('DB_PASSWORD'),
            database=os.getenv('DB_NAME'),
            connection_timeout=5
        )
    except mysql.connector.Error as err:
        print("Database connection failed:", err)
        raise
  • 已尝试PythonAnywhere官方文档提供的方法,问题未解决。
解决方法

通过建立SSH隧道实现外部环境对PythonAnywhere数据库的访问,最终代码如下:

def start_ssh_tunnel():
    global tunnel
    if tunnel is None or not tunnel.is_active:
        tunnel = sshtunnel.SSHTunnelForwarder(
            ('ssh.pythonanywhere.com'),
            ssh_username=os.getenv('SSH_USER'),
            ssh_password=os.getenv('SSH_PASS'),
            remote_bind_address=(os.getenv('DB_HOST'), 3306)
        )
        tunnel.start()
        print("SSH tunnel started")

start_ssh_tunnel()

def get_db_connection():
    if platform.system() != "Linux":
        start_ssh_tunnel()  # 确保隧道处于运行状态
        return MySQLdb.connect(
            host='127.0.0.1',
            port=tunnel.local_bind_port,
            user=os.getenv('DB_USER'),
            passwd=os.getenv('DB_PASSWORD'),
            db=os.getenv('DB_NAME')
        )
    else:
        return MySQLdb.connect(
            host=os.getenv('DB_HOST'),
            user=os.getenv('DB_USER'),
            passwd=os.getenv('DB_PASSWORD'),
            db=os.getenv('DB_NAME')
        )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:52:17