簡體   English   中英

sqlite查詢中的python字符串替換

[英]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的表。
  • IN子句必須帶括號。
  • 你想要三個參數,而不是一個。

試試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM