Gorm: Question: Can't connect to mysql database

Created on 19 Mar 2016  路  4Comments  路  Source: go-gorm/gorm

Hi, I'm not sure if this issue has something to do with gorm, but after 2 hours of debugging I need your help. I'm using the following connection string to connect to a mysql database:

if db, err = gorm.Open("mysql", "root:pass@tcp(localhost:3307)/test?charset=utf8&parseTime=True&loc=Local"); err != nil {
    fmt.Printf("Error connecting to DB: %s", err)
}

This gives me on Mac OS El Capitan:
listen tcp: lookup tcp/: nodename nor servname provided, or not known

The strange thing is that the connection works fine on my Ubuntu machine.
My localhost is in /etc/hosts (and I can ping it)... Since the connection string looks OK, do you have any hints on what could be the problem?

Thank you.

All 4 comments

Have you tried to run a similar piece of code to validate your go application is resolving the name as you think?

addrs, err := net.LookupHost("localhost")

if err == nil {
    for i := 0; i < len(addrs); i++ {
        fmt.Println(addrs[i])
    }
}

Are you using https://github.com/go-sql-driver/mysql as the dialect? refer it for more details.

I think you don't need specify hostname, port, and it should works by default.

root:pass@tcp(127.0.0.1:3306)/test
works for me

Try to do:
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)

func main() {
db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
}
Work for me.
Reference: http://doc.gorm.io/database.html#connecting-to-a-database

Was this page helpful?
0 / 5 - 0 ratings