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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?