1024programmer Java Use Ping to see if DB connection is active in Golang

Use Ping to see if DB connection is active in Golang

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

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/772406

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索