
[英]Is there a compact way to replace a placeholder char in a string with a random element from a list?
[英]Correct way to “select * from tbl where field in ?” and the placeholder is a list without string interpolation
我有一个使用pysqlite的这种形式的查询:
query = "select * from tbl where field1 in ?"
variables = ['Aa', 'Bb']
在查询中,我想这样做:
with conn.cursor() as db:
res = db.execute(query, (variables,)).fetchall()
例如,解释为SQLITE命令行为:
select * from tbl where field1 in ("Aa", "Bb");
但这失败了:
pysqlite3.dbapi2.InterfaceError: Error binding parameter 0 - probably unsupported type.
我了解我可以只使用string.join([mylist]),但这是不安全的。 如何在sqlite中使用sqlite中的占位符参数和列表?
将此与Stackoverflow上的类似问题区分开来 ,他们似乎在使用%s字符串插值法来避免这种情况
问题 :
WHERE field IN ?
并且占位符是没有字符串插值的列表
值是一个int
列表
values = (42, 43, 44)
使用绑定数量准备查询
bindings = '?,'*len(values) QUERY = "SELECT * FROM t1 WHERE id IN ({});".format(bindings[:-1]) print("{}".format(QUERY))
输出 :
SELECT * FROM t1 WHERE id IN (?,?,?);
执行查询
cur.execute (QUERY, values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.