Go - database/sql Basics

Beginner 10/10 Teacher 10/10 Architect 10/10
Tip: See the Sample CRUD API (with Migrations) for a complete DB-backed service.

Setup

Install a driver for your DB (e.g., Postgres, MySQL). Example imports:

import (
  "context"
  "database/sql"
  _ "github.com/lib/pq" // Postgres driver
)

Open and Ping

db, err := sql.Open("postgres", "postgres://user:pass@localhost:5432/app?sslmode=disable")
if err != nil { /* handle */ }
ctx := context.Background()
if err := db.PingContext(ctx); err != nil { /* handle */ }

Query

type User struct{ ID int; Name string }
rows, err := db.QueryContext(ctx, "SELECT id, name FROM users WHERE id > $1", 10)
if err != nil { /* handle */ }
defer rows.Close()
for rows.Next(){
  var u User
  if err := rows.Scan(&u.ID, &u.Name); err != nil { /* handle */ }
}
if err := rows.Err(); err != nil { /* handle */ }

Exec

res, err := db.ExecContext(ctx, "UPDATE users SET name=$1 WHERE id=$2", "Alice", 1)
_ = res

Best Practices

  • Use Context for timeouts and cancellation.
  • Reuse *sql.DB (it manages its own pool).
  • Prefer prepared statements for repeated queries.