我正在尝试将参数传递给注入安全的postgres sql语句。
使用Go中的数据库/ sql包的DB.Query传递arugements时遇到了一些麻烦。
这就是Postgres注册的
STATEMENT: SELECT mc.company_name_full, msc.company_id, msc.cdate, msc.value->>'n_rules', msc.value->>'pct_interfaces_classified'
FROM mn_company AS mc INNER JOIN mn_statistics_company AS msc
ON (mc.id = msc.company_id)
WHERE (msc.value->>'n_rules')::int>0 AND (msc.value->>'pct_interfaces_classified')::int>0 AND
msc.company_id = COALESCE('$1', msc.company_id) AND
mc.company_name_full ~* COALESCE('$2', mc.company_name_full) AND
msc.cdate >= COALESCE('$3', 2017-07-01) AND
msc.cdate <= COALESCE('$4', 2017-09-19)
这是我的函数调用
rows, err := a.DB.Query(*query, qf.companyIDFilter, qf.companyNameFilter, firstDate, secondDate)
所有被粘贴到a.DB.Query中的参数都是指针。
我正在尝试用参数
替换$ 1,$ 2,....答案 0 :(得分:1)
删除占位符周围的引号($1
,$2
,...):
query := `SELECT mc.company_name_full, msc.company_id, msc.cdate, msc.value->>'n_rules', msc.value->>'pct_interfaces_classified'
FROM mn_company AS mc INNER JOIN mn_statistics_company AS msc
ON (mc.id = msc.company_id)
WHERE (msc.value->>'n_rules')::int>0 AND (msc.value->>'pct_interfaces_classified')::int>0 AND
msc.company_id = COALESCE($1, msc.company_id) AND
mc.company_name_full ~* COALESCE($2, mc.company_name_full) AND
msc.cdate >= COALESCE($3, 2017-07-01) AND
msc.cdate <= COALESCE($4, 2017-09-19)`
lib / pq软件包会根据需要自动添加引号。