Background: Not much documentation on MySQLdb Connector
Maybe I'm looking in the wrong places, but there's not much documentation about Python's MySQLdb
family of connectors. Perhaps PEP249 is meant to do the job. Oracle's MySQL/Python connector seems to have much better docs, but at the moment I'm working with mysqlclient (the 3.x version of MySQLdb, which wraps around the C connector).
Named Parameters in MySQLdb: working for single values
After much searching, I stumbled upon beautiful syntax for binding named parameters, so long as they are a single value. For instance (made-up query to simplify the case):
query = """
SELECT...
WHERE
name = %(name)s AND
gender = %(gender)s
"""
parameters = {'name': name, 'gender': gender}
cursor.execute(query, parameters)
This properly escapes the parameters. Terrific.
Named Parameters in MySQLdb: how to use iterables?
Now I'd like to use a set, list or tuple to build queries with IN
. Something like:
query = """
SELECT...
WHERE
gender = %(gender)s AND
name IN %(nameset)s
"""
I found a similar question here but that query doesn't use named parameters (the placeholder is named, but not the iterable).
What am I missing? Would someone know the magic syntax to make this work?
I see in the MySQLdb code that paramstyle
is set to format
rather than pyformat
, but pyformat
does work for single values.
To clarify,
- I am not interested in an answer that just builds a string like
('sophie', 'jane', 'chloe')
and concatenates it to the query. I need bound parameters to guarantee proper escaping. - I am also not interested in concatenating a join that uses
db.escape_string()
, although I may end up going that route if nothing else works.
What I'm really after is a clean idiom that binds named iterable parameters, if there is one.