允许 CleartextPasswords=1 到 DSN

Zl1*_*987 5 mysql go

我正在尝试通过 mysql 连接连接到本地数据库,以通过 Go 启动并运行数据库查询。

当尝试连接时,我遇到了以下错误:

this user requires clear text authentication. If you still want to use it, please add allowCleartextPasswords=1' to your DSN

我的数据库连接如下所示:db, err := sql.Open("sql", "<username>:<password>@tcp(127.0.0.1:<port>)/<dbname>?charset=utf8" )

我可以在哪里包含明文身份验证的依赖项?

col*_*tor 2

既然您提到您正在使用,MySQL我建议利用本机 struct mysql.Config ,如下所示:

loc, _ := time.LoadLocation("America/Chicago") // handle any errors!

c := mysql.Config{
    User:                    "user",
    Passwd:                  "pa55w0rd",
    Net:                     "tcp",
    Addr:                    "127.0.0.1:3306",
    DBName:                  "dbname",
    Params:                  map[string]string{"charset": "utf8"}, // extra params
    AllowCleartextPasswords: true,
    ParseTime:               true, // demo option
    Loc:                     loc,  // demo option
}
fmt.Println(c.FormatDSN())
Run Code Online (Sandbox Code Playgroud)

它将DSN为您正确格式化字符串 - 一路转义任何敏感字符值(例如值loc):

user:pa55w0rd@tcp(127.0.0.1:3306)/dbname?allowCleartextPasswords=true&allowNativePasswords=false&loc=America%2FChicago&parseTime=true&maxAllowedPacket=0&charset=utf8
Run Code Online (Sandbox Code Playgroud)

游乐场示例