[英]Parameterize sql query in go
我有一個簡單的查詢,如下所示。
select json_agg(row_to_json(t)) from (select *
from jobs, companies, locations
where jobs.company_id = companies.id and jobs.location_id = locations.id
$extra
and to_tsvector(jobs.name || ' ' || companies.name || ' ' || locations.name) @@ to_tsquery($1)
and to_tsvector(locations.name) @@ to_tsquery($2)
limit $3) t
但是它在附加查詢方面存在一些問題。 $1
和$2
參數是可選的,基於查詢用戶的請求。 但是仍然,至少在這種情況下, to_tsquery
(postgresql)不支持任何“匹配所有”查詢,例如“ *”,因此我們必須具有整個附加查詢and to_tsvector(locations.name) @@ to_tsquery($2)
並帶有適當的參數還是根本沒有。
這使基於參數的查詢工作變得很麻煩,因為我們必須一直復制相同的查詢並添加其他查詢,而且添加起來很容易。 我有一個使用strings.Replace
的解決方案,可以添加其他查詢,但是如果需要,我們仍然需要對參數進行轉義。 還有其他解決方案可以干凈地完成此操作嗎?
這里有棘手的解決方案,希望對您有所幫助。 此查詢示例使用針對github.com/lib/pq的語法查詢
baseQuery := `
SELECT *
FROM
tableName
WHERE
(name ILIKE $1)`
params := []interface{}{"%" + nameLike + "%"}
// you can add optional criteria using this way
if condition==true {
baseQuery += fmt.Sprintf(` AND student_no=$%d`, len(params)+1)
params = append(params, studentNo)
}
filterQuery := baseQuery + ` ORDER BY contract_no ASC`
if totalLimit != 0 {
filterQuery += fmt.Sprintf(` LIMIT $%d OFFSET $%d`, len(params)+1, len(params)+2)
params = append(params, totalLimit, totalSkip)
}
rows, err := db.Query(filterQuery, params...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.