Gorm: how to open a mysql connection?

Created on 5 Mar 2015  路  5Comments  路  Source: go-gorm/gorm

I have a mysql DB lives on another server. is my connection string correct? I kept getting "Default addr for network '11.11.11.12:3306' unknown", not sure what is wrong and hwo to fix it.

i.DB, err = gorm.Open("mysql", "test:[email protected]:3306/gormtest?charset=utf8@parseTime=true")

Most helpful comment

Should be: id:password@tcp(your-amazonaws-uri.com:3306)/dbname

Please refer https://github.com/go-sql-driver/mysql

All 5 comments

Should be: id:password@tcp(your-amazonaws-uri.com:3306)/dbname

Please refer https://github.com/go-sql-driver/mysql

you should make sure the database you connect (here gormtest) has been created.

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

what is the code if we want open a connection and never close it
should we open in func init(){} ?

what is the code if we want open a connection and never close it
should we open in func init(){} ?

Simply don't call "defer db.Close()" after opening the connection to the database. But, this would be a very bad practice.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

youtwo123 picture youtwo123  路  3Comments

fieryorc picture fieryorc  路  3Comments

Quentin-M picture Quentin-M  路  3Comments

kumarsiva07 picture kumarsiva07  路  3Comments

satb picture satb  路  3Comments