-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
134 lines (111 loc) · 2.55 KB
/
client.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package gosql
import (
"database/sql"
"strconv"
"time"
_ "github.com/go-sql-driver/mysql"
)
const (
timeFormat = "2006-01-02 15:04:05"
)
func New(config *Config) (db *sql.DB, err error) {
db, err = sql.Open("mysql", config.GetConfigString())
return db, err
}
type Config struct {
Host string `json:"host,omitempty"`
Port string `json:"port,omitempty"`
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
Name string `json:"db_name,omitempty"`
Charset string `json:"charset,omitempty"`
}
func (c *Config) GetConfigString() string {
if "" == c.Charset {
c.Charset = "utf8"
}
return c.User + ":" + c.Password + "@tcp(" + c.Host + ":" + c.Port + ")/" + c.Name + "?charset=" + c.Charset
}
func FetchAll(rows *sql.Rows, total int) ([]map[string]string, error) {
columns, err := rows.Columns()
if nil != err {
return nil, err
}
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
var result map[string]string
data := make([]map[string]string, 0, total)
for rows.Next() {
err = rows.Scan(scanArgs...)
if nil != err {
return nil, err
}
var rst string
result = make(map[string]string, len(columns))
for i, col := range values {
switch item := col.(type) {
case int64:
rst = strconv.FormatInt(item, 10)
case string:
rst = item
case []byte:
rst = string(item)
case float64:
strconv.FormatFloat(item, 'f', -1, 64)
case bool:
strconv.FormatBool(item)
case time.Time:
rst = item.Format(timeFormat)
case nil:
rst = ""
}
result[columns[i]] = rst
}
data = append(data, result)
}
return data, nil
}
func FetchRow(rows *sql.Rows) (map[string]string, error) {
columns, err := rows.Columns()
if nil != err {
return nil, err
}
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
result := make(map[string]string)
for rows.Next() {
err = rows.Scan(scanArgs...)
if nil != err {
return nil, err
}
var rst string
for i, col := range values {
if nil == col {
continue
}
switch item := col.(type) {
case int64:
rst = strconv.FormatInt(item, 10)
case string:
rst = item
case []byte:
rst = string(item)
case float64:
strconv.FormatFloat(item, 'f', -1, 64)
case bool:
strconv.FormatBool(item)
case time.Time:
rst = item.Format(timeFormat)
}
result[columns[i]] = rst
}
break
}
return result, nil
}