go-sql-driver使用in语句的问题,防注入问号需要有确定的个数

小熊 Golang评论2,172字数 634阅读2分6秒阅读模式

golang在使用go-sql-driver的时候,如果想用in语句那么?的个数必须是确定的。传入参数即使是字符串1,2,3,4也不行。

A ? can not match anything changing the execution plan of the statement after it is prepared.
https://github.com/go-sql-driver/mysql/issues/176

解决办法,根据传入参数生成确定的问号,比如 ?,?,?

queryEvents := "... WHERE id in(%s) "
ids := []string{"a","b"}
tmpQueryEvents := fmt.Sprintf(queryEvents,strings.Join(strings.Split(strings.Repeat("?", len(ids)),""),","))
fmt.Println(tmpQueryEvents)
rows, err = db.db.Query(tmpQueryEvents, ConvertToInterfaces(ids)...)

query不能传入slience所以必须转换ConvertToInterfaces

func ConvertToInterfaces(slice []string) []interface{} {
    s := make([]interface{}, len(slice))
    for i, v := range slice {
        s[i] = v
    }
    return s
}

费劲。。。

weinxin
公众号
扫码订阅最新深度技术文,回复【资源】获取技术大礼包
小熊