Golang how to open a remote mysql connection?
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:
- 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()
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")
)