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

Colab连接MySQL失败:VS Code可正常连接,报错111连接拒绝

解决Colab无法连接本地MySQL的问题

问题说明

VS Code中运行代码可正常连接本地MySQL服务器,但切换到Colab环境后,出现连接错误:

ERROR: Error while connecting to MySQL: 2003: Can't connect to MySQL server on '127.0.0.1:3310' (111 Connection refused)

相关代码:

def process_row():
    try:
        connection = mysql.connector.connect(host="127.0.0.1", user="root", password="", database="assignment1", port="3310")
        cursor = connection.cursor()

        query = "SELECT * FROM temp_card_new;"
        cursor.execute(query)

        rows = cursor.fetchall()
        connection.close()

        return rows

    except mysql.connector.Error as error:
        print("Error while connecting to MySQL:", error)
        return []

核心原因

Colab运行在谷歌云端服务器上,代码里的127.0.0.1指向的是Colab所在的云服务器本地,而非你自己电脑上的MySQL服务器,因此无法建立连接。

解决步骤

1. 配置MySQL允许远程访问

  • 登录本地MySQL,执行SQL命令授权用户远程访问(可指定IP提升安全性,%代表任意IP):
    GRANT ALL PRIVILEGES ON assignment1.* TO 'root'@'%' IDENTIFIED BY '';
    FLUSH PRIVILEGES;
    
  • 修改MySQL配置文件(my.cnf/my.ini),将bind-address改为0.0.0.0,保存后重启MySQL服务。

2. 获取本地公网IP

  • 浏览器搜索“我的公网IP”,记录下当前的公网地址(例如112.23.45.67)。

3. 开放本地防火墙端口

  • Windows:在Windows Defender防火墙中添加入站规则,允许TCP协议的3310端口访问。
  • Linux:执行命令sudo ufw allow 3310/tcp开放端口。

4. 修改Colab连接代码

将host参数替换为你的公网IP:

connection = mysql.connector.connect(host="112.23.45.67", user="root", password="", database="assignment1", port="3310")

额外注意

  • 公网IP可能动态变化,长期使用建议申请静态IP或使用内网穿透工具(如ngrok)。
  • 开放远程连接存在安全风险,建议设置强密码,或仅允许特定IP访问,使用后及时关闭远程权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:34:50