2

我想执行这样的 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)
4

1 回答 1

4

如果这是您的代码:

known = {'d': 'dval', 'e': 'eval'}
unknown = ['a', 'b', 'c']
# instead of
"SELECT * FROM table WHERE (a like ? OR b like ? OR c like ?) AND (d like :d AND e like :e)"
known.update(dict((str(i), v) for i, v in enumerate(unknown)))
# and use
"SELECT * FROM table WHERE (a like :1 OR b like :2 OR c like :3) AND (d like :d AND e like :e)"

我想你不能同时使用这两种方式,但这是一种选择。

于 2012-04-20T13:55:48.883 回答