How do I use JSONB columns using database/sql with Postgres?

In this guide, we will explore how to use JSONB columns with the Go `database/sql` package when working with PostgreSQL. JSONB is a powerful data type in PostgreSQL that allows you to store JSON in a binary format, which is efficient for both storage and query performance.
Go, JSONB, PostgreSQL, database/sql, Go programming, JSON handling, database management
        
package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"

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

type MyData struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    connStr := "user=username dbname=mydb sslmode=disable"
    db, err := sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Example of inserting a JSONB column
    data := MyData{Name: "Alice", Age: 30}
    jsonData, err := json.Marshal(data)
    if err != nil {
        log.Fatal(err)
    }

    _, err = db.Exec("INSERT INTO my_table(data) VALUES ($1)", jsonData)
    if err != nil {
        log.Fatal(err)
    }

    // Example of querying a JSONB column
    rows, err := db.Query("SELECT data FROM my_table")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    for rows.Next() {
        var jsonData json.RawMessage
        if err := rows.Scan(&jsonData); err != nil {
            log.Fatal(err)
        }

        var item MyData
        if err := json.Unmarshal(jsonData, &item); err != nil {
            log.Fatal(err)
        }

        fmt.Printf("Retrieved: %+v\n", item)
    }

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

Go JSONB PostgreSQL database/sql Go programming JSON handling database management