How do I use JSONB columns using pgx?

In this example, we will demonstrate how to interact with JSONB columns in PostgreSQL using the Go `pgx` library. JSONB is a powerful data type that allows the storage of JSON data in a binary format, which enables indexing and efficient querying.

package main import ( "context" "encoding/json" "fmt" "github.com/jackc/pgx/v4" "log" ) type MyData struct { Name string `json:"name"` Age int `json:"age"` Hobbies []string `json:"hobbies"` } func main() { // Initialize a connection to the PostgreSQL database conn, err := pgx.Connect(context.Background(), "postgres://username:password@localhost:5432/mydb") if err != nil { log.Fatal(err) } defer conn.Close(context.Background()) // Example of inserting JSONB data data := MyData{ Name: "John Doe", Age: 30, Hobbies: []string{"Reading", "Swimming", "Gaming"}, } jsonData, _ := json.Marshal(data) _, err = conn.Exec(context.Background(), "INSERT INTO my_table (data_column) VALUES ($1)", jsonData) if err != nil { log.Fatal(err) } // Example of querying JSONB data var result MyData row := conn.QueryRow(context.Background(), "SELECT data_column FROM my_table WHERE data_column->>'name' = $1", "John Doe") err = row.Scan(&jsonData) if err != nil { log.Fatal(err) } json.Unmarshal(jsonData, &result) fmt.Println(result) }

Go pgx PostgreSQL JSON JSONB Database Go Database Interaction Go JSONB Example