登录
首页 >  Golang >  Go问答

使用 Go 中的参数化查询方法

来源:stackoverflow

时间:2024-02-23 19:12:23 240浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用 Go 中的参数化查询方法》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

用户可以根据许多不同的标准请求产品价格,这将导致它可能访问表中的不同列。我正在循环访问请求的产品并构建一堆查询,但遇到了一些麻烦。

逐一运行它们并将结果组合起来比将它们联合起来需要更长的时间。因此,我尝试构建如下查询,该查询有效且速度快,但现在容易受到注入。

如果没有联盟,是否有更好的方法来做到这一点?或者有没有一种简单的方法可以参数化这样的动态查询?

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= 2
UNION
SELECT 
    price_`+fmt.Sprint(p.type)+` as price,                
  FROM products
  WHERE products.id in ('testid3', 'testid4') and products.store= 1

如果我确定查询是什么,我只会使用 $1、$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.

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 Go 中的参数化查询方法》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>