GoLang ssdb 编写一个model 示例,定义主体和方法,下面的方式是推荐的写法:
1
2
3
4
5
6
type MyDB struct {
*sql.DB
}
func (mdb *MyDB) GetAll() ([]Thing, error) { ... }
func (mdb *MyDB) Get() (id int) (Thing, error) { ... }
下面是用SSDB 作为例子,写个具体的实例:
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
package main
import (
"fmt"
//"reflect"
"github.com/eryx/lessgo/data/hissdb"
)
type User struct {
Id int64
Email string
Username string
Password []byte
}
type Topic struct {
Id int64
Title string
Contenct string
Addtime int64
}
type MyDB struct {
ssdb *hissdb.Connector
}
func (mdb *MyDB) UserGetAll() ([]User, error) {
tmp := make([]User, 0, 10)
fmt.Println("Get all")
return tmp, nil
}
func (mdb *MyDB) UserGet(id int) (User, error) {
user := User{}
fmt.Println("get User id:", id)
mdb.ssdb.Cmd("set", "true", "True")
if mdb.ssdb.Cmd("get", "true").Bool() {
fmt.Println("set bool OK")
}
return user, nil
}
func (mdb *MyDB) TopicGet(id int) (Topic, error) {
topic := Topic{}
fmt.Println("get Topic id:", id)
mdb.ssdb.Cmd("set", "true", "True")
if mdb.ssdb.Cmd("get", "true").Bool() {
fmt.Println("set bool OK")
}
return topic, nil
}
func GetDbMap() (*hissdb.Connector, error) {
conn, err := hissdb.NewConnector(hissdb.Config{
Host: "127.0.0.1",
Port: 8889,
Timeout: 3, // timeout in second, default to 10
MaxConn: 10, // max connection number, default to 1
})
if err != nil {
fmt.Println("Connect Error: %v", err)
return conn, err
}
return conn, nil
}
var mydb MyDB
func main() {
mydb.ssdb, _ = GetDbMap()
mydb.UserGet(1)
defer mydb.ssdb.Close()
fmt.Println("done")
}
本文网址: https://golangnote.com/topic/64.html 转摘请注明来源