-
Notifications
You must be signed in to change notification settings - Fork 0
/
044.DB_SQL_CRUD_example.go
106 lines (86 loc) · 2.31 KB
/
044.DB_SQL_CRUD_example.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"database/sql"
"fmt"
"math/rand"
"reflect"
"time"
_ "github.com/Go-SQL-Driver/MySQL"
)
func TrueRandom(max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max)
}
func main() {
//db, err := sql.Open("mysql", "user:password@/dbname")
db, err := sql.Open("mysql", "root:password@/sreetchat?charset=utf8mb4")
checkErr(err)
//插入資料
stmt, err := db.Prepare("INSERT users SET username=?,age=?,sex=?,timestamp=?")
checkErr(err)
// 執行 query 或 prepared
res, err := stmt.Exec("LKY", TrueRandom(100), "M", time.Now())
checkErr(err)
id, err := res.LastInsertId()
fmt.Println("LastInsertId():", id)
checkErr(err)
//更新資料
stmt, err = db.Prepare("update users set username=? where id=?")
checkErr(err)
res, err = stmt.Exec("LKY_New", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)
//查詢資料
rows, err := db.Query("SELECT * FROM sreetchat.users")
checkErr(err)
for rows.Next() {
var id int
var username string
var age string
var sex string
var iTimeStamp interface{}
err = rows.Scan(&id, &username, &age, &sex, &iTimeStamp)
checkErr(err)
// 如果時間戳記不為空
if nil != iTimeStamp {
// 判斷時間戳記類型
switch v := iTimeStamp.(type) {
case []uint8:
t, _ := time.Parse("2006-01-02 15:04:05", string(v))
//t, _ := time.Parse("yyyy-MM-dd hh:mm:ss", string(v)) //沒用
fmt.Printf("%v, %v, %v, %v, %v, %v\n", id, username, age, sex, t, reflect.TypeOf(v))
case time.Time:
fmt.Printf("%v, %v, %v, %v, %v, %v\n", id, username, age, sex, v, reflect.TypeOf(v))
case string:
//t, err := time.Parse("2006-01-02 15:04:05", v)
t, err := time.Parse(time.Now().String(), v)
if nil != err {
fmt.Printf("%v, %v, %v, %v, %v, %v\n", id, username, age, sex, t, reflect.TypeOf(t))
} else {
fmt.Println(err)
}
}
} else {
fmt.Printf("%v, %v, %v, %v, %v\n", id, username, age, sex, "timestamp is null")
}
}
//刪除資料
stmt, err = db.Prepare("DELETE FROM users WHERE id=7810")
checkErr(err)
fmt.Println(stmt)
fmt.Println("=NULL:", err)
res, err = stmt.Exec()
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if nil != err {
fmt.Errorf("%s", err)
panic(err)
}
}