Go Academy · Lesson

database/sql and Drivers

DB setup, QueryRow, Scan, and connection pools

Lesson 1 of 413 steps

database/sql and Drivers is a free Go Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

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

Yes — any 3 lessons of the Go Academy learning path, including “database/sql and Drivers”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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