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
+28.4k Golang : How to verify uploaded file is image or allowed file types
+4.7k Linux/Unix/PHP : Restart PHP-FPM
+18.3k Golang : Determine if directory is empty with os.File.Readdir() function
+8.9k Golang : Setting variable value with ldflags
+9k Golang : Use regular expression to get all upper case or lower case characters example
+12.6k Golang : Gin framework accept query string by post request example
+5.6k Golang : Gargish-English language translator
+3.9k Which content-type(MIME type) to use for JSON data
+13.7k Golang : Get HTTP protocol version example
+12k Golang : Get user input until a command or receive a word to stop
+29.7k Golang : Get local IP and MAC address
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?