How to Use Context with Database Queries in Go

Use context.WithTimeout and QueryRowContext to prevent database queries from hanging indefinitely.

Pass a context.Context as the first argument to your database query methods to enable cancellation and timeouts. This ensures your application stops waiting for slow queries if the context expires.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

var result string
err := db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = ?", 1).Scan(&result)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        log.Println("Query timed out")
    }
}