简体   繁体   English

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

[英]Python sqlite operation,SQL statement 'where field in (1,2)' syntax error

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

The error is: sqlite3.OperationalError: near ":id": syntax error错误是: sqlite3.OperationalError: near ":id": syntax error

My search of the Official Python documentation and Google failed to find the answer:我搜索官方 Python 文档和谷歌未能找到答案:

https://docs.python.org/3/library/sqlite3.html https://docs.python.org/3/library/sqlite3.html

How should arguments be passed? 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 the second query, you would need actually separate placeholders for every value in the IN clause.在第二个查询中,您实际上需要为IN子句中的每个值使用单独的占位符。 In addition, I would use ?另外,我会使用? here:这里:

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())

The SQL query generated by the above script is:上述脚本生成的 SQL 查询为:

select * from test_tab where test_num = ? AND in (?, ?)

and we bind (111, 1, 2) to the three ?我们将(111, 1, 2)绑定到三个? placeholders.占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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