-
-
Notifications
You must be signed in to change notification settings - Fork 511
/
db_sqlite3.go
63 lines (52 loc) · 928 Bytes
/
db_sqlite3.go
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
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "./sqlite3.db")
if err != nil {
panic(err)
}
defer db.Close()
_, err = db.Exec("CREATE TABLE persons (name TEXT)")
if err != nil {
panic(err)
}
tx, err := db.Begin()
if err != nil {
panic(err)
}
stmt, err := tx.Prepare("INSERT INTO persons VALUES (?)")
if err != nil {
panic(err)
}
defer stmt.Close()
names := []string{"alice", "bob", "charlie"}
for _, name := range names {
_, err := stmt.Exec(name)
if err != nil {
panic(err)
}
}
tx.Commit()
rows, err := db.Query("SELECT rowid AS id, name FROM persons")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
panic(err)
}
fmt.Println(id, name)
}
err = rows.Err()
if err != nil {
panic(err)
}
}