SELECT * FROM Table WHERE Id IN (1,2,3,4,5,6)
请注意,您不能在参数化查询中插入整个列表 - 例如,带有包含 '1,2,3,4,5,6' 的参数的 WHERE Id IN (?) 不会产生您想要的结果。
避免动态构建 SQL 字符串(并可能将自己暴露于SQL Injection)的一个好方法是动态构建参数数量,然后将它们连接到 SQL 中。
Python 和 SQLite 的完整示例(尽管此方法可用于任何语言和任何 SQL 数据库引擎):
ids = [1, 2, 3, 4, 5, 6]
params = tuple(ids) # because sqlite wants the parameters in tuple format
paramstring = ', '.join(['?' for dummyp in ids])
# paramstring now contains '?, ?, ?, ?, ?, ?'
# - the same number of '?' as the number of ids
sql = 'SELECT * FROM Table WHERE Id IN (' + paramstring + ')'
# sql now contains 'SELECT * FROM Table WHERE Id IN (?, ?, ?, ?, ?, ?)'
conn = sqlite3.connect(':memory:')
cursor = conn.execute(sql, params)
# You can now iterate through the cursor to get your data