-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_some_data_and_query.go
More file actions
79 lines (66 loc) · 1.47 KB
/
add_some_data_and_query.go
File metadata and controls
79 lines (66 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
"github.com/jackc/pgx"
)
func Connect(dsn string, maxConn int) *pgx.ConnPool {
pgConfig, err := pgx.ParseURI(dsn)
if err != nil {
fmt.Sprintf("could not parse DSN: %s", dsn)
}
conn, err := pgx.NewConnPool(pgx.ConnPoolConfig{
ConnConfig: pgConfig,
MaxConnections: maxConn,
})
if err != nil {
fmt.Println("could not create connection pool")
}
return conn
}
func Query(db pgx.ConnPool) []string {
q := `SELECT doc from public.jsonb_test;`
fmt.Println(q)
res := []string{}
rows, err := db.Query(q)
if err != nil {
fmt.Sprintf("could not run query: %s", q)
}
defer rows.Close()
for rows.Next() {
var r string
err = rows.Scan(&r)
if err != nil {
fmt.Println(err)
}
res = append(res, r)
}
return res
}
func Insert(db pgx.ConnPool) {
q := `INSERT INTO public.jsonb_test (id, doc) VALUES ($1, $2)`
stmt, err := db.Prepare("json_insert", q)
if err != nil {
fmt.Sprintf("could not create prepared statement: %s", q)
}
new_profile := `
{
"id": 4, "profileName": "Nana",
"hobbies": ["yoyos"],
"location": {"state": "OR", "zip": 97206, "cool": true}
}
`
res, err := db.Exec(stmt.SQL, 4, new_profile)
if err != nil {
fmt.Sprintf("could not execute SQL: %s", q)
}
fmt.Println(res)
}
func main() {
ip := ""
dsn := fmt.Sprintf("postgres://demo_admin:postgres@%s:5432/demo", ip)
pool := 5
db := Connect(dsn, pool)
fmt.Println(Query(*db))
Insert(*db)
fmt.Println(Query(*db))
}