-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (55 loc) · 1.18 KB
/
main.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
64
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3" // 导入SQLite3驱动
)
func main() {
// 打开数据库连接
db, err := sql.Open("sqlite3", "./test.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// 创建表
createTableSQL := `CREATE TABLE IF NOT EXISTS projects (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT,
"description" TEXT
);`
_, err = db.Exec(createTableSQL)
if err != nil {
log.Fatal(err)
}
// 插入数据
stmt, err := db.Prepare("INSERT INTO projects(name, description) VALUES(?, ?)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
_, err = stmt.Exec("My Project", "This is a sample project")
if err != nil {
log.Fatal(err)
}
// 查询数据
rows, err := db.Query("SELECT id, name, description FROM projects")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name, description string
err = rows.Scan(&id, &name, &description)
if err != nil {
log.Fatal(err)
}
fmt.Println(id, name, description)
}
// 检查查询过程中可能出现的错误
err = rows.Err()
if err != nil {
log.Fatal(err)
}
}