你好...我正在尝试向查询添加一个参数,但出现此错误:
"errorMessage": "{'S': 'ERROR', 'V': 'ERROR', 'C': '42601', 'M': 'syntax error at or near \”$2\"', 'P': '3793', 'F': 'scan.l', 'L': '1146', 'R': 'scanner_yyerror'}"
这有效:
import pg8000
account_id = 1234
sql = “”"
SELECT *
FROM samples
WHERE account_id = %s
AND delete_date IS NULL
ORDER BY date DESC
“”"
cursor.execute(sql, (account_id,))
但事实并非如此:
import pg8000
account_id = 1234
start_date = query_string_params['start-date'] if 'start-date' in query_string_params else None
// start_date format is: '2025-02-04'
filters = “"
if start_date is not None:
filters = filters + f" AND DATE(sample_date) >= '{start_date}'"
sql = “”"
SELECT *
FROM samples
WHERE account_id = %s
AND delete_date IS NULL
%s
ORDER BY date DESC
“”"
cursor.execute(sql, (account_id, filters))
知道我做错了什么吗?
SQL 参数必须是值,而不是 SQL 代码本身。过滤器是动态查询的一部分,而不是参数值。
这是可行的,但可能会增加 SQL 注入攻击的风险,因为
start_date
输入不会被 pg 驱动程序转义。转换
start_date
为相同的格式并将sample_date
过滤器写为filters = filters + f" AND DATE(sample_date) >= %s"
也可以工作,但DATE(sample_date)
可能会根据检查的记录数量引入性能损失。