我正在关注教程here和here,但我无法连接到mySQL安装附带的test
数据库。我可以通过命令行连接到mySql。我错过了什么?当我运行下面的代码时,我收到错误“无法ping”:
package main
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "/test")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Println("cannot ping")
return
}
}
答案 0 :(得分:2)
例如,将{MySQL}用户名和密码替换为user
和password
,
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user:password@/test")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Ping")
}
输出:
Ping