Is it possible to safely ping the database to check if my golang application is still connected or is there a better solution than this? I read somewhere that we shouldn’t use .ping() to determine connection loss.
Thanks.
1> Mark..:
It might be better to perform a simple query and check the results. The Ping() method would work Safe to use, but can be implemented by the database driver.
See Ping()
2> Kimmo Hintik..:
I would say Ping() is the way to do this if you need it to be run only when the program starts Query connections are tested separately.
Generally, I just trust the database/sql to automatically try to reconnect in case you perform a query against the database and the connection fails. So you can use Open to check if the database connection args are correct and use trust query to return an error in case the connection is lost.
People say that Ping() can cause a race condition, but can’t show me how to do it or provide a suitable alternative if a connection test is needed.
This is how Gorm (the widely used Golang ORM project) implements it:
// Send a ping to make sure the database connection is alive. if d, ok := dbSQL.(*sql.DB); ok { if err = d.Ping(); err != nil { d.Close() } } return
https://github.com/jinzhu/gorm