sqlite 查询中的 python 字符串替换

发布于 2024-10-20 17:52:40 字数 235 浏览 0 评论 0原文

我正在尝试使用 IN 语句返回与字符串列表之一匹配的结果,

例如

strings = ['string1', 'string2', 'string3'] c.execute('select count(*) from table where foo in ?', strings)

我知道这是不正确的并且不起作用,但我希望它突出显示我正在尝试做的事情...

i'm trying to use an IN statement to return results which match one of a list of strings

for example

strings = ['string1', 'string2', 'string3']
c.execute('select count(*) from table where foo in ?', strings)

i know this is incorrect and doesnt work but i hope that it highlights what im trying to do...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那请放手 2024-10-27 17:52:40

你不能那样做。存在三个问题:

  • 除非在表名周围使用反引号,否则不能拥有名为 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 + ')'

You can't do that. There are three problems:

  • You can't have a table called table unless you use backticks around the table name.
  • An IN clause must have parentheses.
  • You want three parameters, not one.

Try this instead:

sql = 'SELECT COUNT(*) FROM yourtable WHERE foo IN (?, ?, ?)'

If the number of strings is variable, use this instead:

params = ','.join('?' for x in strings)
sql = 'SELECT COUNT(*) FROM yourtable WHERE foo IN (' + params + ')'
后来的我们 2024-10-27 17:52:40

您可以按照 @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')

You can do a ','.join(strings) as @Mark Byers suggests, that works most times. However if the number of strings is very long it will fail because SQL queries have bounded length.

Another way of doing it is creating a temp table, inserting there all the strings and doing a join to perform the intersection, something like

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文