简体   繁体   English

当参数有时可以为NULL时,如何参数化SQL查询?

[英]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.

相关问题 在Python中参数化SQL查询 - Parameterize an SQL query in Python 如何正确地参数化查询和转义输入以防止SQL注入? - How to properly parameterize query and escape inputs properly to prevent SQL injection? 如何在 BigQuery SQL 中安全地参数化表/列名称? - How can I safely parameterize table/column names in BigQuery SQL? 将SQL查询中的列表作为参数时如何在Python中执行查询 - How to execute query in Python when list in SQL query as parameter SQL 数据库使用 JDBC + 参数化 SQL 查询 + Databricks - SQL Database using JDBC + parameterize SQL Query + Databricks 使用查询参数创建 SQL 命令,该参数检查 NULL 和其他值 - Create SQL command with a query parameter that checks for NULL but also for other values 如何安全地参数化动态python mysql查询? - How do I securely parameterize a dynamic python mysql query? 如何使用python优雅地参数化SQL DELETE语句? - How to use python to elegantly parameterize a SQL DELETE statement? 我应该如何在pysqlite中参数化列名以避免SQL注入 - How should I parameterize column names in pysqlite to avoid SQL Injection 当 LIKE 变量/模式可以更改时如何向 SQL 询问查询 (?, '%?%', ...) - How to ask a query to SQL when the LIKE variable/pattern can change (?, '%?%', ...)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM