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

Django连接cPanel托管MySQL报错:OperationalError: MySQL Connection not available

解决Django连接cPanel托管MySQL数据库的OperationalError问题

核心问题定位

你的Django应用与MySQL数据库部署在不同服务器,但settings.py中HOST设为localhost——这会让Django尝试连接自身服务器的MySQL实例,而非cPanel托管的远程数据库,这是导致连接失败的主要原因。

具体解决步骤

  • 修正数据库HOST配置
    登录cPanel后台,找到MySQL管理相关模块(如MySQL Databases或Remote MySQL),获取数据库的远程连接地址(通常是cPanel服务器的公网IP,或提供的专用数据库域名)。修改settings.py:

    DATABASES = {
        'default': {
            'ENGINE': 'mysql.connector.django',
            'NAME': 'your_db_name',       
            'USER': 'your_db_user',      
            'PASSWORD': 'your_db_password',  
            'HOST': 'cpanel_server_ip_or_db_domain',  # 替换为实际远程地址
            'PORT': '3306',                     
        }
    }
    
  • 允许Django服务器IP远程访问cPanel MySQL
    在cPanel的Remote MySQL工具中,添加Django应用所在服务器的公网IP(可通过curl ifconfig.me命令获取),授权该IP访问目标数据库。

  • 排查mysql-connector-python版本兼容性
    版本8.4.0可能与当前Django版本存在适配问题,尝试降级到稳定版本:

    pip uninstall mysql-connector-python
    pip install mysql-connector-python==8.0.36
    
  • 直接测试数据库连接(排除Django层面问题)
    编写简单脚本验证连接,确认凭据和网络无问题:

    import mysql.connector
    from mysql.connector import errorcode
    
    try:
        cnx = mysql.connector.connect(
            user='your_db_user',
            password='your_db_password',
            host='cpanel_server_ip_or_db_domain',
            database='your_db_name'
        )
        print("连接成功!")
        cnx.close()
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("用户名或密码错误")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("数据库不存在")
        else:
            print(err)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:42:36