0Pricing
Go Academy · Lesson

database/sql and Drivers

DB setup, QueryRow, Scan, and connection pools

database/sql and Drivers is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

database/sql overview

database/sql is Go's standard database abstraction layer. It manages a connection pool and works with any database via a driver plugin.

Registering a driver

Import the driver package for its side effects (driver registration). Then open a connection:

import _ "github.com/lib/pq" // PostgreSQL driver

db, err := sql.Open("postgres", "postgres://user:pass@localhost/mydb?sslmode=disable")
if err != nil { log.Fatal(err) }
defer db.Close()

sql.Open vs db.Ping

sql.Open does not connect — it validates the DSN. Call db.Ping() or db.PingContext(ctx) to verify the connection is alive.

if err := db.Ping(); err != nil { log.Fatal(err) }

Querying rows

Use db.QueryContext to execute a SELECT and scan rows:

rows, err := db.QueryContext(ctx, "SELECT id, name FROM users WHERE active = $1", true)
if err != nil { return err }
defer rows.Close()
for rows.Next() {
    var id int; var name string
    rows.Scan(&id, &name)
}

Single row query

db.QueryRowContext returns a *Row for queries expected to return at most one result:

var name string
err := db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)
if errors.Is(err, sql.ErrNoRows) { /* not found */ }

Executing mutations

Use db.ExecContext for INSERT, UPDATE, DELETE. It returns a Result with affected rows and last insert ID.

result, err := db.ExecContext(ctx, "INSERT INTO users(name) VALUES($1)", name)
if err != nil { return err }
id, _ := result.LastInsertId()

Prepared statements

Prepare a statement once and execute it many times efficiently:

stmt, err := db.PrepareContext(ctx, "SELECT id FROM users WHERE email = $1")
defer stmt.Close()
for _, email := range emails {
    row := stmt.QueryRowContext(ctx, email)
}

Connection pool settings

Configure the pool for production:

db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5 * time.Minute)

Checking rows.Err()

After the rows loop, always check rows.Err() — the loop may have exited early due to a network error.

if err := rows.Err(); err != nil { return err }

Null values

Use sql.NullString, sql.NullInt64, etc. to handle database NULL values that would otherwise panic when scanned into a non-pointer Go type.

var bio sql.NullString
rows.Scan(&bio)
if bio.Valid { fmt.Println(bio.String) }

drivers list

Popular drivers: github.com/lib/pq (PostgreSQL), github.com/go-sql-driver/mysql (MySQL), modernc.org/sqlite (SQLite, pure Go).

Quick Check

Why must you always call rows.Close() and check rows.Err() after a query?

Recap: database/sql

Key points:

  • Import driver with _ for side effects; sql.Open + Ping
  • QueryContext → rows.Next + Scan + rows.Close + rows.Err
  • ExecContext for mutations; QueryRowContext for single rows
  • SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime for pool

Frequently asked questions

Is the “database/sql and Drivers” lesson free?

Yes — the full text of “database/sql and Drivers” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “database/sql and Drivers”?

DB setup, QueryRow, Scan, and connection pools You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “database/sql and Drivers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. database/sql and Drivers
  2. sqlx: Struct Scanning and Named Queries
  3. pgx: High-Performance PostgreSQL Driver
  4. Transactions and Migrations
← Back to Go Academy