[英]Python sqlite operation,SQL statement 'where field in (1,2)' syntax error
Python sqlite 操作,SQL 語句 'where field in (1,2)' 語法錯誤
錯誤是: sqlite3.OperationalError: near ":id": syntax error
我搜索官方 Python 文檔和谷歌未能找到答案:
https://docs.python.org/3/library/sqlite3.html
arguments應該如何通過?
'''first create test.db:table and field
CREATE TABLE test_tab (
id INTEGER PRIMARY KEY ASC,
test_num INT,
test_field TEXT
);
'''
import sqlite3
con = sqlite3.connect('test.db')
con.set_trace_callback(print) # start the debug
d = [
(111,'aaa'),
(111,'bbb'),
(111,'ccc'),
(444,'ddd')
]
sql = "insert into `test_tab` (`test_num`, `test_field`) values (?,?)"
cursor = con.executemany(sql, d)
con.commit() # Execute successfully
#####################
# wrong code begin,why sql 'in ()' is wrong?
sql = "SELECT * from `test_tab` where `test_num`=:num AND `id` in :id"
par = {'num': 111, 'id': (1,2)} # The number of 'id' parameters is uncertain
x = con.execute(sql, par)
print(x.fetchall())
在第二個查詢中,您實際上需要為IN
子句中的每個值使用單獨的占位符。 另外,我會使用?
這里:
num = 111
ids = (1, 2)
par = (num,) + ids
sql = "select * from test_tab where test_num = ? AND id in "
in_clause = '(?' + ', ?'*(len(ids) - 1) + ')'
sql = sql + in_clause
x = con.execute(sql, par)
print(x.fetchall())
上述腳本生成的 SQL 查詢為:
select * from test_tab where test_num = ? AND in (?, ?)
我們將(111, 1, 2)
綁定到三個?
占位符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.