参考官方文档
https://go.dev/doc/tutorial/database-access
var db *sql.DB func main() { // Capture connection properties. cfg := mysql.Config{ User: os.Getenv("DBUSER"), Passwd: os.Getenv("DBPASS"), Net: "tcp", Addr: "127.0.0.1:3306", DBName: "recordings", } // Get a database handle. var err error db, err = sql.Open("mysql", cfg.FormatDSN()) if err != nil { log.Fatal(err) } pingErr := db.Ping() if pingErr != nil { log.Fatal(pingErr) } fmt.Println("Connected!") }
报错:
zego@zegodeMacBook-Pro-53 data-access % go run main.go [mysql] 2021/12/16 11:23:02 connector.go:95: could not use requested auth plugin 'mysql_native_password': this user requires mysql native password authentication. 2021/12/16 11:23:02 this user requires mysql native password authentication. exit status 1
解决方法:添加 AllowNativePasswords: true,
cfg := mysql.Config{ User: os.Getenv("DBUSER"), Passwd: "123456", Net: "tcp", Addr: "127.0.0.1:3306", DBName: "recordings", AllowNativePasswords: true, }
参考文档中说明该参数默认为 true,我这边不知道何原因为 false
当设为 false 表示不允许使用 MySQL 原生密码方法
参数文档
https://github.com/go-sql-driver/mysql#dsn-data-source-name
解决方案参考链接
https://github.com/go-sql-driver/mysql/issues/815