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

SQL连接器配置错误引发MySQL连接失败,寻求故障原因

Ballerina连接MySQL出现Connection refused错误的排查方向

我运行以下Ballerina代码:

import ballerina/http;
import ballerina/sql;
import ballerinax/mysql;
import ballerinax/mysql.driver as _;

type isValid record {
    boolean valid;
    string nic;
};

type Person record {
    string mic;
    @sql:Column {name: "firstname"}
    string firstName;
    @sql:Column {
        name: "lastname"
    }
    string lastName;
};

configurable string database = ?;
configurable string username = ?;
configurable string host = ?;

mysql:Client mysqlEp = check new (host = host, user = username, database = database);

service / on new http:Listener(9090) {
    resource function get checkNic/[string nic]() returns isValid|error? {

        Person|error person = check mysqlEp->queryRow(`select * from nic_details where nic=${nic.trim()}`);

        if (person is error) {
            isValid result = {
                valid: false,
                nic: nic
            };
            return result;
        } else {
            isValid result = {
                valid: true,
                nic: nic
            };
            return result;
        }
    }

    resource function get path() {

    }
}

出现如下错误:

error: Error in SQL connector configuration: Failed to initialize pool: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. Caused by :Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. Caused by :Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. Caused by :Connection refused

已确认使用默认端口3306,XAMPP显示MySQL服务器正运行于该端口,主机设置为localhost,以下是错误的可能原因及排查方向:

可能原因

  • IPv6解析冲突:部分系统中localhost会优先解析为IPv6地址::1,但XAMPP的MySQL可能仅绑定了IPv4的127.0.0.1,导致连接被拒。尝试将host配置改为127.0.0.1强制使用IPv4连接。
  • 防火墙/安全软件拦截:本地防火墙、杀毒软件可能阻断了Ballerina进程访问3306端口。临时关闭防火墙或添加Ballerina进程的访问权限,测试是否能正常连接。
  • MySQL用户权限不足:当前配置的数据库用户可能没有从localhost或127.0.0.1连接的权限。登录MySQL执行SELECT user, host FROM mysql.user;,查看对应用户的host字段是否为localhost或%;若不是,执行GRANT ALL PRIVILEGES ON 你的数据库名.* TO '你的用户名'@'localhost';并执行FLUSH PRIVILEGES;刷新权限。
  • 连接器与MySQL版本不兼容:使用的ballerinax/mysql连接器版本可能与XAMPP中的MySQL版本不匹配。检查连接器版本,尝试升级或降级到兼容的版本。
  • 端口实际被占用或配置不符:虽然XAMPP显示运行在3306,但可能存在其他进程占用该端口,或MySQL配置文件(my.cnf/my.ini)中修改了端口。执行netstat -ano | findstr :3306(Windows)或lsof -i :3306(Linux/macOS),确认端口占用情况及实际监听端口。
  • 连接参数缺失:代码中创建mysql:Client时未显式指定端口,虽然默认是3306,但可以尝试添加port = 3306参数,确保连接配置完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:52:48