[英]How to parameterize SQL query when the parameter can sometimes be NULL?
With pyodbc
I can parametrize the query like this; 使用
pyodbc
我可以像这样对查询进行参数化;
value = "testval"
query = \
"""
SELECT *
FROM TestTable
WHERE Column = ?;
"""
cursor.execute(query, value)
But the problem is that if the value
is None, the query should look like this; 但是问题在于,如果该
value
None,则查询应如下所示;
value = None
query = \
"""
SELECT *
FROM TestTable
WHERE Column IS NULL;
"""
cursor.execute(query)
So how should the query look like when the value
can either be None or a string; 因此,当
value
可以为None或字符串时,查询应为什么样?
value = get_value() # can return a string or None
query = \
"""
SELECT *
FROM TestTable
WHERE Column ???????????
"""
cursor.execute(query, value)
The solution is to use the ISO/ANSI standard NULL
-safe comparison: 该解决方案是使用ISO / ANSI标准
NULL
-safe比较:
WHERE Column IS NOT DISTINCT FROM ?
Not all databases support this, so you can also use: 并非所有数据库都支持此功能,因此您还可以使用:
WHERE Column = ? OR (Column IS NULL AND ? IS NULL)
If you are reluctant to pass the parameter twice, you can include it in the FROM
clause: 如果您不愿意两次传递参数,则可以将其包含在
FROM
子句中:
. . .
FROM . . . CROSS JOIN
(SELECT ? as compColumn) params
WHERE (Column = params.compColumn0 or (Column IS NULL and params.compColumn IS NULL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.