通过pyodbc我可以参数化这样的查询;
pyodbc
value = "testval" query = \ """ SELECT * FROM TestTable WHERE Column = ?; """ cursor.execute(query, value)
但是问题在于,如果avalue为None,则查询应如下所示;
value
value = None query = \ """ SELECT * FROM TestTable WHERE Column IS NULL; """ cursor.execute(query)
因此,当查询value可以为None或字符串时,查询应如何?
value = get_value() # can return a string or None query = \ """ SELECT * FROM TestTable WHERE Column ??????????? """ cursor.execute(query, value)
解决方案是使用ISO / ANSI标准-安全NULL比较:
NULL
WHERE Column IS NOT DISTINCT FROM ?
并非所有数据库都支持此功能,因此您还可以使用:
WHERE Column = ? OR (Column IS NULL AND ? IS NULL)
如果您不愿意两次传递参数,则可以在FROM子句中包含它:
FROM
. . . FROM . . . CROSS JOIN (SELECT ? as compColumn) params WHERE (Column = params.compColumn0 or (Column IS NULL and params.compColumn IS NULL)