问题遇到的现象和发生背景
我刚开始学习go语言,读取配置文件到map[string]string 中,返回map,map 可以正常遍历出 key和value 。但取值拼接却不成功, 请帮忙看看!
用代码块功能插入代码,请勿粘贴截图
func Itodb() {
//1、数据据库初始化
conf := initDB()
//2、连接数据库
dbparam := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", conf["user"], conf["pwd"], conf["host"], conf["port"], conf["dbName"])
fmt.Println(dbparam) //无法正确拼接 无法 连接数据库
db, err := sql.Open("mysql", dbparam)
if err != nil {
fmt.Println(err)
}
//运行完关闭数据库
defer db.Close()
//数据库连接
err = db.Ping()
if err != nil {
fmt.Println(err)
return
} else {
fmt.Println("数据库连接成功!")
}
}
//读取配置文件返回map
//配置文件结构database
//user:root
//pwd:root
//host:localhost
//...
func initDB() map[string]string {
//读取数据库配置文件
path := "./Config/database"
text := files.FileRead(path)
ts := strings.Split(text, "\n")
DBconfig := make(map[string]string, 1000)
for _, value := range ts {
if strings.Count(value, ":") > 0 {
v := strings.Split(value, ":")
DBconfig[v[0]] = v[1]
}
}
return DBconfig
}
运行结果及报错内容
运行结果
)/go6localhost
: getaddrinfow: The specified class was not found.
我的解答思路和尝试过的方法
遍历map key和value 正常
charset === utf8
user === root
type === mysql
dbName === go
pwd === root
port === 3306
tablePrefix === ""
host === localhost
1、使用指针问题依旧
2、使用map直接赋值连接成功
DBconfig["user"] = "root"
DBconfig["pwd"] = "root"
DBconfig["host"] = "localhost"
DBconfig["port"] = "3306"
DBconfig["dbName"] = "go"
3、map值用变量接收 问题依旧
4、不使用map 直接使用变量赋值 连接成功
我想要达到的结果
正常读取配置值 进行数据库连接