Python sqlite3使用named和qmark参数执行

时间:2012-04-20 12:47:40

标签: python sqlite

我想执行这样的SQL语句:

SELECT * FROM table WHERE spam LIKE ? AND eggs LIKE :eggs

Python sqlite3模块文档说:

  

Cursor.execute(sql [,parameters])

     

[...]

     

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)

1 个答案:

答案 0 :(得分:2)

如果这是您的代码:

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)"

我猜你不能两种方式一起使用,但这是另一种选择。