import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { // Open a connection to the database db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/mydb") if err != nil { panic(err.Error()) } // Ping the database to test the connection err = db.Ping() if err != nil { panic(err.Error()) } fmt.Println("Successfully connected to the database") }
import ( "database/sql" "fmt" _ "github.com/lib/pq" ) func main() { // Open a connection to the database db, err := sql.Open("postgres", "user=postgres dbname=mydb password=secret sslmode=disable") if err != nil { panic(err.Error()) } // Ping the database to test the connection err = db.Ping() if err != nil { panic(err.Error()) } fmt.Println("Successfully connected to the database") }In this example, the code opens a connection to a PostgreSQL database using the "github.com/lib/pq" package. It then calls the Ping function to test the connection. If the Ping function returns an error, it will be thrown as a panic. Otherwise, the message "Successfully connected to the database" will be printed to the console. In conclusion, the Ping function is part of the "database/sql" package in Go, which provides a generic interface around SQL databases. By calling Ping, you can test whether you can successfully connect to the database. The package library for Ping is "database/sql".