Golang : How to check if a connection to database is still alive ?
Problem :
How to check if a connection to database is still alive ?
Solution :
Use DB.Ping function. For example :
package main
import (
"database/sql"
"fmt"
// without the underscore _, you will get imported but not
// used error message
_ "github.com/go-sql-driver/mysql"
"os"
)
func main() {
// connect to our database server with data source name
// data source name configuration has the following parameters :
// [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
// example config :
// user:password@tcp(127.0.0.1:3306)/database
conn, err := sql.Open("mysql", "db_username:db_password@protocol(address:port_num)/database_name")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = conn.Ping()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// if no error. Ping is successful
fmt.Println("Ping to database successful, connection is still alive")
conn.Close()
// this part should fail
err = conn.Ping()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// if no error. Ping is successful
fmt.Println("Ping to database successful, connection is still alive")
}
Output :
Ping to database successful, connection is still alive
sql: database is closed
exit status 1
References :
See also : Golang : Connect to database (MySQL/MariaDB) server
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.5k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+10.2k Golang : Convert file content to Hex
+23.7k Golang : Use regular expression to validate domain name
+17.2k Golang : Check if IP address is version 4 or 6
+13.3k Golang : Count number of runes in string
+6.3k Golang : Handling image beyond OpenCV video capture boundary
+9.3k Golang : Scramble and unscramble text message by randomly replacing words
+16.6k Golang : Gzip file example
+5.3k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+9.8k Golang : Translate language with language package example
+9k Golang : Write multiple lines or divide string into multiple lines
+4.5k Mac OSX : Get disk partitions' size, type and name