项目中执行很复杂的sql语句,底层封装的太死,不确定到底最终执行的sql语句字符串长啥样,虽然手工替换也能够得到,但毕竟效率太低,特别是当参数很多的时候,几乎是不可能,也非常容易出错,写了一个工具function,解决这个需求:
package main
import (
"fmt"
"strconv"
"reflect"
"strings"
)
type MoviePublishMeta struct {
stringvalue string
typevalue string
}
func QueryRow(sql string, args ...interface{}) string {
if len(args) > 0 {
argsMap := make(map[int]MoviePublishMeta)
for i := 0; i < len(args); i++ {
switch reflect.TypeOf(args[i]).Name() {
case "int": {
argsMap[i] = MoviePublishMeta{ // 初始化同时直接添加值
stringvalue: strconv.Itoa(args[i].(int)),
typevalue: reflect.TypeOf(args[i]).Name(),
}
break;
}
case "string": {
argsMap[i] = MoviePublishMeta{ // 初始化同时直接添加值
stringvalue: "'"+args[i].(string)+"'",
typevalue: reflect.TypeOf(args[i]).Name(),
}
break;
}
default: {
break;
}
}
}
for k, v := range argsMap {
tempstr:=sql
sql=strings.Replace(tempstr, "$"+strconv.Itoa(k+1), v.stringvalue, -1 )
}
}
return sql
}
func main() {
// txt := QueryRow("select id, media_url from data.photo where storage_filename=$1 and cur=$2 limit 1","/vkimages/2021-06-09-23/0000000060c0e5781d41c8ed8a000017.png",35)
txt := QueryRow("select id, media_url from data.photo where storage_filename=$1 and cur=$2 limit 1","/vkimages/2021-06-09-23/0000000060c0e5781d41c8ed8a000017.png","youming")
fmt.Println(txt)
}
两个测试例子的输出如下:
(1):
select id, media_url from data.photo where storage_filename='/vkimages/2021-06-09-23/0000000060c0e5781d41c8ed8a000017.png' and cur=35 limit 1
(2):
select id, media_url from data.photo where storage_filename='/vkimages/2021-06-09-23/0000000060c0e5781d41c8ed8a000017.png' and cur='youming' limit 1
很开心的达到了目的