项目中执行很复杂的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
很开心的达到了目的
本文介绍了一个Go语言编写的工具函数,用于处理复杂SQL查询中的参数替换。该函数接受一个SQL模板字符串和任意数量的参数,根据参数类型自动进行字符串或整数的转换,并将模板中的占位符替换为实际值,有效避免手动替换的低效和易错问题。示例展示了如何使用该工具处理包含字符串和整数的SQL查询。
891

被折叠的 条评论
为什么被折叠?



