db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname") defer db.Close()
func connectDB() (*sql.DB, error) { db, err := sql.Open("postgres", "user=foo password=bar dbname=mydb sslmode=disable") if err != nil { return nil, err } return db, nil } func main() { db, err := connectDB() if err != nil { log.Fatal(err) } defer db.Close() // perform database actions here }This example demonstrates a more complex usage of the `Close` method. The `connectDB` function is used to establish a database connection and return the `*sql.DB` object. The `main` function calls `connectDB` and checks for any errors before performing database actions. Once the main function has completed, the `defer db.Close()` statement ensures that the database connection is properly closed. Package library: `database/sql`