亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號