-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper.go
More file actions
45 lines (42 loc) · 1.07 KB
/
Copy pathhelper.go
File metadata and controls
45 lines (42 loc) · 1.07 KB
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
package gosql
import (
"errors"
"strings"
)
func formatSql(cmd string, args ...interface{}) (string, error) {
// 先转为为小写
lowercmd := strings.ToLower(cmd)
// 找到关键字 values
tmp_index := strings.Index(lowercmd, " values")
if tmp_index < 0 {
return "", errors.New("insert sql error")
}
// 找到关键字 后面的第一个 (
start_index := strings.Index(cmd[tmp_index:], "(")
if start_index < 0 {
return "", errors.New("sql error: eg: insert into table(name) values(?)")
}
end_index := strings.LastIndex(cmd, ")")
if start_index < 0 {
return "", errors.New("sql error: eg: insert into table(name) values(?)")
}
value := cmd[tmp_index+start_index : end_index+1]
//查看一行数据有多少列
column := 0
for _, v := range strings.Split(value[1:len(value)-1], ",") {
opt := strings.Trim(v, " ")
if opt == "?" {
column++
}
}
// 总共多少参数
count := len(args)
if count%column != 0 {
return "", errors.New("args error")
}
addcmd := "," + value
for i := 1; i < count/column; i++ {
cmd = cmd + addcmd
}
return cmd, nil
}