I want to execute an SQL statement like this:
SELECT * FROM table WHERE spam LIKE ? AND eggs LIKE :eggs
Python sqlite3 module documentation says:
Cursor.execute(sql[, parameters])
[…]
The sqlite3 module supports two kinds of placeholders: question marks (qmark style) and named placeholders (named style).
But is there a way to use both qmark style and named style?
SOLUTION (thanks to jadkik94):
params = ["a","b","c"]
kparams = {'d':"d", 'e':"e"}
sql = "SELECT * FROM table WHERE (a LIKE ? OR b LIKE ? OR c LIKE ?) AND (d LIKE :d AND e LIKE :e)"
sql = sql.replace("?", ":{}").format(*range(sql.count("?")))
# >>> sql
# "SELECT * FROM table WHERE (a like :0 OR b like :1 OR c like :2) AND (d like :d AND e like :e)"
kparams.update(dict(map(lambda x: (str(x[0]), x[1]), enumerate(params))))
# >>> kparams
# {'0': 'a', '1': 'b', '2': 'c', 'd': 'd', 'e': 'e'}
c.execute(sql, kparams)
If this is your code:
I guess you cannot use both ways together, but that’s one alternative.