Skip to content

Commit 57e5007

Browse files
authored
Merge pull request #1313 from Jaculabilis/json-example
Fix json example
2 parents bb8d0b2 + cff37b4 commit 57e5007

1 file changed

Lines changed: 49 additions & 1 deletion

File tree

_example/json/json.go

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ func main() {
3333
}
3434
defer db.Close()
3535

36-
_, err = db.Exec(`create table foo (tag jsonb)`)
36+
// Using a json-typed column
37+
// Verify type: `create table foo (tag text) strict`
38+
_, err = db.Exec(`create table foo (tag json)`)
3739
if err != nil {
3840
log.Fatal(err)
3941
}
@@ -78,4 +80,50 @@ func main() {
7880
log.Fatal(err)
7981
}
8082
fmt.Println(country)
83+
84+
// Using a jsonb-typed column
85+
// Verify type: `create table bar (tag blob) strict`
86+
_, err = db.Exec(`create table bar (tag jsonb)`)
87+
if err != nil {
88+
log.Fatal(err)
89+
}
90+
91+
stmt, err = db.Prepare("insert into bar(tag) values(jsonb(?))")
92+
if err != nil {
93+
log.Fatal(err)
94+
}
95+
defer stmt.Close()
96+
_, err = stmt.Exec(`{"name": "mattn", "country": "japan"}`)
97+
if err != nil {
98+
log.Fatal(err)
99+
}
100+
_, err = stmt.Exec(`{"name": "michael", "country": "usa"}`)
101+
if err != nil {
102+
log.Fatal(err)
103+
}
104+
105+
err = db.QueryRow("select tag->>'country' from bar where tag->>'name' = 'mattn'").Scan(&country)
106+
if err != nil {
107+
log.Fatal(err)
108+
}
109+
fmt.Println(country)
110+
111+
err = db.QueryRow("select json(tag) from bar where tag->>'name' = 'mattn'").Scan(&tag)
112+
if err != nil {
113+
log.Fatal(err)
114+
}
115+
116+
fmt.Println(tag.Name)
117+
118+
tag.Country = "日本"
119+
_, err = db.Exec(`update bar set tag = jsonb(?) where tag->>'name' == 'mattn'`, &tag)
120+
if err != nil {
121+
log.Fatal(err)
122+
}
123+
124+
err = db.QueryRow("select tag->>'country' from bar where tag->>'name' = 'mattn'").Scan(&country)
125+
if err != nil {
126+
log.Fatal(err)
127+
}
128+
fmt.Println(country)
81129
}

0 commit comments

Comments
 (0)