[英]python string substitution in sqlite query
我正在尝试使用IN语句返回与字符串列表中的一个匹配的结果
例如
strings = ['string1', 'string2', 'string3']
c.execute('select count(*) from table where foo in ?', strings)
strings = ['string1', 'string2', 'string3']
c.execute('select count(*) from table where foo in ?', strings)
我知道这是不正确的,但不起作用,但我希望它突出了我想要做的...
你不能这样做。 有三个问题:
table
的表。 试试这个:
sql = 'SELECT COUNT(*) FROM yourtable WHERE foo IN (?, ?, ?)'
如果字符串的数量是可变的,请改用:
params = ','.join('?' for x in strings)
sql = 'SELECT COUNT(*) FROM yourtable WHERE foo IN (' + params + ')'
你可以做一个','.join(strings)
就像@Mark Byers建议的那样,大多数时候都有效。 但是,如果字符串的数量很长 ,它将失败,因为SQL查询具有有限的长度。
另一种方法是创建临时表,插入所有字符串并执行连接以执行交集,类似于
c.execute('CREATE TEMP TABLE strings (s STRING)')
c.executemany('INSERT INTO strings (s) VALUES (?)', ((s,) for s in strings))
c.execute('SELECT COUNT(*) FROM table JOIN strings ON table.foo == strings.s')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.