理解这是一个老问题,未来的访问者应该知道,如果在列表中的字符串而不是整数上使用上面和评论中的答案,可能会带来一些 SQL 注入风险。我没有创建一个表来专门测试下面的代码,但在其他查询中使用了类似的代码。
仅供参考 - 其他 SQL 驱动程序,如 pyodbc 和 psycopg2 使用 ' %s ' 作为占位符,但只有一个 ' ? ' 使用 fdb 对我有用。
cur = con.cursor()
list = [1,2,3]
# Create a placeholder list containing a '?' for each element
placeholders = []
for i in list:
placeholders.append('?')
# Change placeholder list to string of question marks separated by commas
ph_text = ', '.split(placeholders)
# Create sql statement
# Can use format here without risk of SQL injection because it is only ', ' and '?'
sql = """SELECT * FROM data d WHERE d.field IN ({0})""".format(ph_text)
# Execute the statement, passing list items in tuple for fdb to escape (avoid SQL-injection)
# Note that the list is converted to a tuple,
# whereas the SQL in the question had the list as the first (and only) tuple element
cur.execute(sql, tuple(list))