I want to make a new connection with the sql server on localhost so that I can able to get the data from the sql server. but there is some problem while doing connection.
error :- [mysql] 2019/02/11 15:30:00 driver.go:81: net.Error from Dial()': dial tcp serverPort:3306: connect: connection timed out
And the code I'm using is
func ConnectMsqlDb() (db *sql.DB, err error) {
db, err = sql.Open("mysql",
fmt.Sprintf("%s:%s@tcp(%s:"+SqlDbPort+")/"+SqlDatabase,
SqlUsername, SqlPassword, SqlServerPort))
fmt.Println("OPEN", db, err)
if err != nil {
return nil, err
}
//defer db.Close()
fmt.Println("PING:-", err)
err = db.Ping()
fmt.Println("PING:-", err)
if err != nil {
return nil, err
}
return db, nil
}
Can you help me to get out from this problem?
If you're trying to connect to a remote server you need its full address:
<username>:<pw>@tcp(<HOST>:<port>)/<dbname>
In your example I don't see the host anywhere, so it tries to connect to a server running on localhost (with port given by SqlServerPort
).
func main() {
db, err := sql.Open("mysql",
"user:password@tcp(127.0.0.1:3306)/hello")
if err != nil {
log.Fatal(err)
}
defer db.Close()
}
You'll need to replace 127.0.0.1
with the actual IP address (or hostname) of your remote server.