使用Gorm连接MySQL出现connection refused错误求助
Gorm连接MySQL报错「dial tcp :0: connect: connection refused」排查
问题现象
使用Gorm连接MySQL时触发错误:dial tcp :0: connect: connection refused,但通过命令行可正常连接目标数据库,代码连接失败。
相关信息
application.yaml配置
applications: url: 127.0.0.1 userName: dog passWord: 123456 dbName: douyin port: 3306
MySQL初始化Go代码
// InitMySql Initialize connection database func InitMySql() (err error) { var c conf // Get yaml configuration parameters conf := c.getConf() // Splice the yaml configuration parameters into the url to connect to the database dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", conf.UserName, conf.PassWord, conf.Url, conf.Port, conf.DbName, ) // Connect to database SqlSession, err = gorm.Open(DRIVER, dsn) if err != nil { panic(err) } // Verify whether the database connection is successful. If successful, there is no exception return SqlSession.DB().Ping() }
端口监听状态
root@ezra-virtual-machine:/home/ezra# netstat -an | grep 3306 tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:33060 0.0.0.0:* LISTEN
排查分析
错误dial tcp :0: connect: connection refused的核心原因是数据库连接地址中的端口被解析为0,导致尝试连接无效端口。结合你的配置和代码,问题大概率出在以下两点:
- 配置层级不匹配:yaml中所有配置项都嵌套在
applications节点下,但代码中直接通过conf.UserName、conf.Port读取字段,说明conf结构体未正确对应yaml的嵌套层级,导致Port等字段未被正确读取,最终在DSN中填充为空,MySQL客户端将空端口解析为0。 - 字段类型解析错误:若
conf.Port字段定义为int类型,yaml中port是数字,但代码中用%s(字符串占位符)格式化,一旦读取失败会默认填充0,同样会导致DSN中端口为0。
解决方案
1. 修正配置结构体与yaml层级匹配
假设你使用gopkg.in/yaml.v3解析配置,调整结构体定义以匹配yaml的嵌套结构:
type conf struct { Applications struct { Url string `yaml:"url"` UserName string `yaml:"userName"` PassWord string `yaml:"passWord"` DbName string `yaml:"dbName"` Port string `yaml:"port"` // 用string避免类型转换问题 } `yaml:"applications"` }
然后在代码中读取对应字段:
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", conf.Applications.UserName, conf.Applications.PassWord, conf.Applications.Url, conf.Applications.Port, conf.Applications.DbName, )
2. 调试DSN生成结果
在生成DSN后添加打印语句,确认实际连接字符串是否正确:
fmt.Println("Generated DSN:", dsn)
如果输出的DSN中端口部分为空或为0,说明配置读取确实存在问题,需进一步排查getConf()方法的实现逻辑。
3. 可选:调整yaml结构(简化层级)
如果不需要applications嵌套节点,直接将配置项放在yaml根节点:
url: 127.0.0.1 userName: dog passWord: 123456 dbName: douyin port: 3306
此时conf结构体可直接定义为:
type conf struct { Url string `yaml:"url"` UserName string `yaml:"userName"` PassWord string `yaml:"passWord"` DbName string `yaml:"dbName"` Port string `yaml:"port"` }
内容的提问来源于stack exchange,提问作者Eliot
相关产品推荐
相关产品推荐

