Skip to content

Commit 64bbe62

Browse files
committed
add example
1 parent cdc8095 commit 64bbe62

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

_example/json/json.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package main
2+
3+
import (
4+
"database/sql"
5+
"database/sql/driver"
6+
"encoding/json"
7+
"fmt"
8+
_ "github.com/mattn/go-sqlite3"
9+
"log"
10+
"os"
11+
)
12+
13+
type Tag struct {
14+
Name string `json:"name"`
15+
Country string `json:"country"`
16+
}
17+
18+
func (t *Tag) Scan(value interface{}) error {
19+
return json.Unmarshal([]byte(value.(string)), t)
20+
}
21+
22+
func (t *Tag) Value() (driver.Value, error) {
23+
b, err := json.Marshal(t)
24+
return string(b), err
25+
}
26+
27+
func main() {
28+
os.Remove("./foo.db")
29+
30+
db, err := sql.Open("sqlite3", "./foo.db")
31+
if err != nil {
32+
log.Fatal(err)
33+
}
34+
defer db.Close()
35+
36+
_, err = db.Exec(`create table foo (tag jsonb)`)
37+
if err != nil {
38+
log.Fatal(err)
39+
}
40+
41+
stmt, err := db.Prepare("insert into foo(tag) values(?)")
42+
if err != nil {
43+
log.Fatal(err)
44+
}
45+
defer stmt.Close()
46+
_, err = stmt.Exec(`{"name": "mattn", "country": "japan"}`)
47+
if err != nil {
48+
log.Fatal(err)
49+
}
50+
_, err = stmt.Exec(`{"name": "michael", "country": "usa"}`)
51+
if err != nil {
52+
log.Fatal(err)
53+
}
54+
55+
var country string
56+
err = db.QueryRow("select tag->>'country' from foo where tag->>'name' = 'mattn'").Scan(&country)
57+
if err != nil {
58+
log.Fatal(err)
59+
}
60+
fmt.Println(country)
61+
62+
var tag Tag
63+
err = db.QueryRow("select tag from foo where tag->>'name' = 'mattn'").Scan(&tag)
64+
if err != nil {
65+
log.Fatal(err)
66+
}
67+
68+
fmt.Println(tag.Name)
69+
70+
tag.Country = "日本"
71+
_, err = db.Exec(`update foo set tag = ? where tag->>'name' == 'mattn'`, &tag)
72+
if err != nil {
73+
log.Fatal(err)
74+
}
75+
76+
err = db.QueryRow("select tag->>'country' from foo where tag->>'name' = 'mattn'").Scan(&country)
77+
if err != nil {
78+
log.Fatal(err)
79+
}
80+
fmt.Println(country)
81+
}

0 commit comments

Comments
 (0)