您好,欢迎来到爱够旅游网。
搜索
您的当前位置:首页go语言带位置描述的字符串格式化

go语言带位置描述的字符串格式化

来源:爱够旅游网

    项目中执行很复杂的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
很开心的达到了目的

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igbc.cn 版权所有 湘ICP备2023023988号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务