How do I execute queries and scan rows using pgx?

Learn how to execute queries and scan rows using the pgx library in Go. This powerful PostgreSQL driver allows for efficient database interactions.
Go, pgx, PostgreSQL, database queries, Go database interaction

package main

import (
    "context"
    "fmt"
    "github.com/jackc/pgx/v4"
    "log"
)

func main() {
    // Create a connection to the database
    conn, err := pgx.Connect(context.Background(), "postgres://username:password@localhost:5432/mydatabase")
    if err != nil {
        log.Fatal("Unable to connect to database:", err)
    }
    defer conn.Close(context.Background())

    // Execute a SQL query
    rows, err := conn.Query(context.Background(), "SELECT id, name FROM users")
    if err != nil {
        log.Fatal("Query failed:", err)
    }
    defer rows.Close()

    // Scan the rows
    for rows.Next() {
        var id int
        var name string
        err := rows.Scan(&id, &name)
        if err != nil {
            log.Fatal("Row scan failed:", err)
        }
        fmt.Printf("ID: %d, Name: %s\n", id, name)
    }

    // Check for any errors encountered during iteration
    if err := rows.Err(); err != nil {
        log.Fatal("Row iteration error:", err)
    }
}

Go pgx PostgreSQL database queries Go database interaction