Question

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.

Was it helpful?

Solution

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:

  1. 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.
  2. 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)
  3. Confusingly, 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()

OTHER TIPS

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")

)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top