简体   繁体   English

Python MySQLdb查询参数“ IS NULL”而不是“ = NULL”

[英]Python MySQLdb query parameters “IS NULL” instead of “= NULL”

I'm working on a Python script to import data to a MySQL database. 我正在研究将数据导入MySQL数据库的Python脚本。 I use MySQLdb to execute my queries. 我使用MySQLdb执行查询。

I also use a function to set a query and its data with named parameters to be automatically replaced inside the request, such as: 我还使用一个函数来设置查询及其带有命名参数的数据,以便在请求中自动替换该命名参数,例如:

req = "SELECT * FROM sample WHERE `id` = %(id)s and `param1` = %(param1)s"
data = {'id': 15, 'param1': None}
cursor.execute(req, data)

I really like this way because I'm using the same data dict for 3 or 4 queries. 我真的很喜欢这种方式,因为我对3个或4个查询使用相同的数据dict

The problem is when I try to make a WHERE condition with None value, it does replace my None by NULL but I would like it to be able to replace a `param1` = NULL by `param1` IS NULL , so that the condition evaluates to true. 问题是当我尝试使用None值创建WHERE条件时,它确实用NULL代替了我的None ,但是我希望它能够用`param1` IS NULL代替`param1` = NULL `param1` IS NULL ,以便条件求值真实。

Is there any way to solve this issue directly? 有什么办法可以直接解决这个问题? Or can I use just the parameter replace (without executing the query), then do a replace on my own ( = NULL to IS NULL ), and then execute the query. 或者我可以只使用参数replace(不执行查询),然后自己进行替换( = NULLIS NULL ),然后执行查询。

You can do something like the following. 您可以执行以下操作。

def query(params):
    # Make sure it's hardcoded and malicious user can't overwrite it
    param_whitelist = 'id', 'param1'

    sql = '''
        SELECT * 
        FROM sample 
        WHERE {placeholders}
    '''
    placeholders = ' AND '.join(
        '`{field}` {op} %s'.format(field=k, op='IS' if params[k] is None else '=') 
        for k in param_whitelist)
    sql = sql.format(placeholders=placeholders)

    cursor.execute(sql, params)
    return cursor


data = {'id': 15, 'param1': None}
print([r for r in query(data)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM