Query Rows With database/sql

Run a parameterised query and scan each row into a struct, closing rows and checking the iteration error so resources are not leaked.

GoData Fetching

Code

gosnippet
33 lines
package store

import (
	"context"
	"database/sql"
)

type User struct {
	ID    int64
	Email string
}

func ListActiveUsers(ctx context.Context, db *sql.DB) ([]User, error) {
	rows, err := db.QueryContext(ctx,
		"SELECT id, email FROM users WHERE active = $1 ORDER BY id", true)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []User
	for rows.Next() {
		var user User
		if err := rows.Scan(&user.ID, &user.Email); err != nil {
			return nil, err
		}
		users = append(users, user)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return users, nil
}

Inside the snippet

The working surface is the function ListActiveUsers — everything else is wiring.

Repetition is confined to for rows.Next() — the rest of the file is straight-line. Every fallible call checks err != nil (3 sites), so an error is handled where it happens rather than bubbling invisibly. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Points of care

  • error is part of the return tuple, so every caller decides what failure means.

Using it

The entry-point signature is func ListActiveUsers(ctx context.Context, db *sql.DB) ([]User, error)

The surface worth importing is ListActiveUsers; the helpers around it are private to the snippet.

Key statements

if err := rows.Err(); err != nil {
	return nil, err
}
if err != nil {
	return nil, err
}
users = append(users, user)

Interactive Tools for This Topic

FAQ

What is the error handling style?
By return value: each fallible call hands back an `error`, checked at 3 places here.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `context`, `database/sql`. The file defines `ListActiveUsers` at load time.