如何使用Go连接到mysql服务器并运行sql-driver? [英] How do I connect to mysql server with Go and go-sql-driver?
本文介绍了如何使用Go连接到mysql服务器并运行sql-driver?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在按照这里的教程进行操作和此处,但我是无法连接到mySQL安装附带的 test
数据库。我可以通过命令行连接到mySql。我错过了什么?当我运行下面的代码时,出现错误无法ping:
I am following the tutorials here and here but I am unable to connect to the test
database that came with mySQL installation. I can connect to mySql through the command line. What am I missing? When I run the code below I get the error "cannot 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
}
}
推荐答案
例如,用您的MySQL用户名和密码替换 user
和 password
这两个字,
For example, substitute your MySQL user name and password for the words user
and 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
这篇关于如何使用Go连接到mysql服务器并运行sql-driver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文