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
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
[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.
To set up remote connection to your database, go to Site Tools > Site > MySQL > Remote. After that fill in the IP address or hostname from which you want to connect. You can also add a Label for them. This will allow you to connect to the database server via a remote MySQL client.
Select Connections from the SQL navigation menu. In the Authorized networks section, click Add network and enter the IP address of the machine where the client is installed. Note: The IP address of the instance and the mysql client IP address you authorize must be the same IP version: either IPv4 or IPv6. Click Done.
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/
There are a few things that might help:
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.mysql.New()
which can open connections using the format you've listed above: db := mysql.New(proto, "", addr, user, pass, dbname)
sql.Open
doesn't actually open a connection, it just creates a db resource. You can verify that it's working by running db.Ping()
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")
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With