在sqlite查询中进行python字符串替换
我想用一个IN语句来返回与一组字符串匹配的结果。
比如说:
strings = ['string1', 'string2', 'string3']
c.execute('select count(*) from table where foo in ?', strings)
我知道这样写是不对的,不能正常工作,但我希望这能说明我想做的事情……
2 个回答
2
你可以像@Mark Byers建议的那样使用 ','.join(strings)
,这在大多数情况下都能奏效。不过,如果字符串的数量非常多,就会失败,因为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')
6
你不能这样做。这里有三个问题:
- 你不能直接用
table
作为表的名字,除非你在表名周围加上反引号。 - IN 语句必须用括号包起来。
- 你需要三个参数,而不是一个。
试试这个:
sql = 'SELECT COUNT(*) FROM yourtable WHERE foo IN (?, ?, ?)'
如果字符串的数量是可变的,可以用这个:
params = ','.join('?' for x in strings)
sql = 'SELECT COUNT(*) FROM yourtable WHERE foo IN (' + params + ')'