Reputation: 992
I'm working on a Python script to import data to a MySQL database. I use MySQLdb to execute my queries.
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.
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.
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.
Upvotes: 0
Views: 798
Reputation: 25253
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)])
Upvotes: 2