Lesson 24 of 60 · Go
Working with Databases – `database/sql` and Drivers
Duration: 25 minutes
Database Access
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
The database/sql package provides a generic API; you need a driver (e.g., github.com/lib/pq for PostgreSQL).
import (
"database/sql"
_ "github.com/lib/pq"
)
func main() {
dsn := "user=alice password=secret dbname=mydb sslmode=disable"
db, err := sql.Open("postgres", dsn)
if err != nil { log.Fatal(err) }
defer db.Close()
// Ping to verify connection
if err := db.Ping(); err != nil { log.Fatal(err) }
// Query
rows, _ := db.Query("SELECT id, name FROM users WHERE active=$1", true)
defer rows.Close()
for rows.Next() {
var id int
var name string
rows.Scan(&id, &name)
fmt.Println(id, name)
}
}
Using sqlx for convenience
$ go get github.com/jmoiron/sqlx
import "github.com/jmoiron/sqlx"
var db *sqlx.DB
// db.Get(&dest, "SELECT …", args…)