繁体   English   中英

Python sqlite 操作,SQL 语句 'where field in (1,2)' 语法错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM