MySQL Golang如何开启远程mysql连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23550453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Golang how to open a remote mysql connection?
提问by The user with no hat
I'm trying to connect to remote mysql database using go and the database/sql package. I find the go/mysql documentation confusing. It seems there is no single example how to connect to a remote host. Like everyone would use localhost. So far I have this
我正在尝试使用 go 和 database/sql 包连接到远程 mysql 数据库。我发现 go/mysql 文档令人困惑。似乎没有一个例子来说明如何连接到远程主机。就像每个人都会使用本地主机一样。到目前为止我有这个
import (
"database/sql"
_ "github.com/ziutek/mymysql/godrv"
db, err := sql.Open("mymysql", "tcp:"+dbHost*dbName+"/"+user+"/"+pass)
defer db.Close()
Based on the docs from https://github.com/ziutek/mymysql
基于https://github.com/ziutek/mymysql的文档
[PROTOCOL_SPECFIIC*]DBNAME/USER/PASSWD
//
// where protocol specific part may be empty (this means connection to
// local server using default protocol). Currently possible forms:
// DBNAME/USER/PASSWD
// unix:SOCKPATH*DBNAME/USER/PASSWD
// unix:SOCKPATH,OPTIONS*DBNAME/USER/PASSWD
// tcp:ADDR*DBNAME/USER/PASSWD
// tcp:ADDR,OPTIONS*DBNAME/USER/PASSWD
I also tried
我也试过
db, err := sql.Open("mymysql", "tcp:"+dbHost, dbName+"/"+user+"/"+pass)
and it's not working either. The whole syntax seems cryptic.
它也不起作用。整个语法似乎很神秘。
回答by dethtron5000
These sites are both really helpful in understanding Go SQL: https://github.com/go-sql-driver/mysql/(even if you are using a different driver) and http://go-database-sql.org/
这些站点都对理解 Go SQL 非常有帮助:https: //github.com/go-sql-driver/mysql/(即使您使用不同的驱动程序)和http://go-database-sql.org/
There are a few things that might help:
有几件事可能会有所帮助:
- The connection string for
sql.Open()
is in DSN format.db, err := sql.Open("mysql", "<username>:<pw>@tcp(<HOST>:<port>)/<dbname>")
works for me for my connections. Check the use of parenthesis for TCP connections. - The driver you are using has the command
mysql.New()
which can open connections using the format you've listed above:db := mysql.New(proto, "", addr, user, pass, dbname)
- Confusingly,
sql.Open
doesn't actually open a connection, it just creates a db resource. You can verify that it's working by runningdb.Ping()
- 的连接字符串
sql.Open()
采用 DSN 格式。db, err := sql.Open("mysql", "<username>:<pw>@tcp(<HOST>:<port>)/<dbname>")
为我的连接工作。检查 TCP 连接括号的使用。 - 您正在使用的驱动程序具有
mysql.New()
可以使用上面列出的格式打开连接的命令:db := mysql.New(proto, "", addr, user, pass, dbname)
- 令人困惑的是,
sql.Open
实际上并没有打开连接,它只是创建了一个 db 资源。您可以通过运行来验证它是否正常工作db.Ping()
回答by user2712873
Following statement works for me:
以下陈述对我有用:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
db, err := sql.Open("mysql", "db_user:password@tcp(localhost:3306)/my_db")
)
)