我想执行这样的 SQL 语句:
SELECT * FROM table WHERE spam LIKE ? AND eggs LIKE :eggs
Python sqlite3 模块文档说:
Cursor.execute(sql[, 参数])
[...]
sqlite3 模块支持两种占位符:问号(qmark 样式)和命名占位符(命名样式)。
但是有没有办法同时使用 qmark 样式和命名样式?
解决方案(感谢 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)