Created
October 22, 2024 14:30
-
-
Save Harkishen-Singh/6fca24c750778acf624126c316bc7532 to your computer and use it in GitHub Desktop.
A Go program to interact with a JSONB type in PostgreSQL database using the pgx library and standard a Go byte slice.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
"os" | |
"github.com/jackc/pgx/v5" | |
) | |
type Student struct { | |
Name string | |
Details []byte | |
} | |
type Details struct { | |
Age uint8 `json:"age"` | |
Height uint16 `json:"height"` | |
} | |
func main() { | |
urlExample := "postgres://postgres:pass@localhost:5433/test_jsonb_pgx" | |
conn, err := pgx.Connect(context.Background(), urlExample) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) | |
os.Exit(1) | |
} | |
defer conn.Close(context.Background()) | |
details := Details{ | |
Age: 25, | |
Height: 180, | |
} | |
b, err := json.Marshal(details) | |
if err != nil { | |
panic(err) | |
} | |
student := Student{ | |
Name: "HS", | |
Details: b, | |
} | |
_, err = conn.Exec(context.Background(), "insert into student values ($1, $2)", student.Name, student.Details) | |
if err != nil { | |
panic(err) | |
} | |
// Read the details. | |
var newName string | |
var newDetails []byte | |
err = conn.QueryRow(context.Background(), "select name, details from student").Scan(&newName, &newDetails) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(newName, string(newDetails)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment