为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Go 中对动态查询进行参数化

如何在 Go 中对动态查询进行参数化

Go
慕标5832272 2022-10-24 09:38:12
用户可以根据许多不同的标准请求产品价格,这将导致它可能访问表中的不同列。我正在遍历请求的产品并构建一堆查询,但遇到了一些麻烦。一个一个地运行它们并组合结果比将它们联合起来需要更长的时间。因此,我尝试构建如下查询,它有效且速度快,但现在容易受到注入的影响。没有联盟有没有更好的方法来做到这一点?或者有没有一种简单的方法可以参数化这样的动态查询?    var fullQuery string    var counter int    for i, d:= range dataMap{    if counter != 0 {        fullQuery = fullQuery + " UNION "    }    var records string    for _, p := range d{        records = records + `'` + string(p) + `',`    }    recordLength:= len(records)    if recordLength> 0 && records [recordLength-1] == ',' {        records = records[:recordLength-1]    }    counter++    fullQuery = fullQuery + fmt.Sprintf(`SELECT     price_`+fmt.Sprint(p.type)+` as price,                  FROM products  WHERE products.id in (%s) and products.store= %s  `, records, p.store)}err := sqlx.Select(db, &dataStruct, fullQuery)所以,在某些情况下,我可能会有以下查询:SELECT     price_`+fmt.Sprint(p.type)+` as price,                  FROM products  WHERE products.id in (%s) and products.store= %s在其他情况下(取决于请求),我可能会有这样的事情:SELECT     price_`+fmt.Sprint(p.type)+` as price,                  FROM products  WHERE products.id in ('testid1', 'testid2') and products.store= 2UNIONSELECT     price_`+fmt.Sprint(p.type)+` as price,                  FROM products  WHERE products.id in ('testid3', 'testid4') and products.store= 1如果我确定查询是什么,我只会使用 $1、$2 等,但我不认为我可以在这里,因为我不知道会有多少参数并且它们都需要不同.
查看完整描述

1 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

弄清楚了,未经测试的粗略示例,说明我如何最终做到这一点,以防其他人遇到这种情况。


 var counter int = 1

 var parameters []interface{}


 for _, d:= range data{

    if counter != 1 {

        fullQuery = fullQuery + " UNION "

    }

    fullQuery = fullQuery + fmt.Sprintf(`

SELECT 

    price_`+fmt.Sprint(d.type)+` as price,                

  FROM products

  WHERE products.id = ANY($%v) and products.store= $%d

  

`, counter, counter+1)

   counter+=2

   parameters = append(parameters, pq.Array(d.ids), d.store)


}


err := sqlx.Select(db, &dataStruct, fullQuery, parameters...)



Will still need to validate column names prior to querying to prevent injection.


查看完整回答
反对 回复 2022-10-24
  • 1 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号