sql.Open
- Go course
- Advanced
- Lesson 26/68
- 4 min
Learn to open a database connection with sql.Open.
sql.Open
sql.Open(driver, dsn) returns a *sql.DB and an error. Note: Open does not connect; it only validates the settings. Call Ping to try a real connection:
db, err := sql.Open("postgres", "postgres://user:pass@localhost/app?sslmode=disable")
if err != nil { log.Fatal(err) }
defer db.Close()
if err := db.Ping(); err != nil { log.Fatal(err) }DSN and secrets
The DSN (data source name) depends on the driver: MySQL uses user:pass@tcp(host:3306)/db, PostgreSQL a URL format. Read the password from an environment variable instead of writing it in code:
dsn := os.Getenv("DATABASE_URL")
db, err := sql.Open("postgres", dsn)Practice Unknown driver
Call sql.Open("yok", "x"). An unregistered driver returns an error; if err != nil, print fmt.Println("sürücü yok").
Starter code
package main
import (
"database/sql"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"database/sql"
"fmt"
)
func main() {
_, err := sql.Open("yok", "x")
if err != nil {
fmt.Println("sürücü yok")
}
}Expected output
sürücü yok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>sql.Open</code> do when the database is down?
- Usually no error; it appears on the first query or Ping Correct answer
- It panics immediately
- It waits forever
- It starts the database
Explanation: Open is lazy; the connection opens on first need. A Ping at startup reveals problems early.
2 Test the connection
if err := db.____(); err != nil {
log.Fatal(err)
}
if err := db.Ping(); err != nil {
log.Fatal(err)
}
Explanation: Ping tries to establish a real connection and returns an error if there is a problem.
3 Function and role
| Term | Meaning |
|---|---|
sql.Open |
Prepares the pool |
db.Ping |
Tests the connection |
db.Close |
Closes the pool |
os.Getenv |
Reads the DSN from the environment |