0

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.

1 Answer 1

2

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)])
Sign up to request clarification or add additional context in comments.

1 Comment

@m.nachury Initially I've pasted not the latest version of the snippet where param_whitelist is not used. It's fixed in the update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.