我的意思是这样的:
from django.db import connection
cursor=connection.cursor()
cursor.execute('SELECT * FROM mytable where id IN (%s)', [params])
参数不能只是可迭代的——它不起作用。 由于数据库处理程序转义值,不能也采用 CSV 格式。
如何在 IN 中使用占位符?
按 CSV 是错误的,我的意思是对于 params=['1','2','3','4','5']
c.execute('select * from mytable where id in (%s)', [','.join(params)])
将产生:
select * from mytable where id in ('1,2,3,4,5')
但正确的 sql 是:
select * from mytable where id in (1,2,3,4,5)
用占位符似乎很难实现。
请您参考如下方法:
你不能为此使用 IN 因为确实,in 需要一个整数序列,但是 ORM 将列表转换为 ARRAY,如果你使用 join 你会得到一个字符串。
解决方案是使用等效的 ANY。格式略有不同,但这应该适合您:
c.execute('select * from mytable where id = ANY(%s)', [params])
给定 params = [1, 2, 3, 4, 5],生成的 SQL 将是:
SELECT * FROM mytable where id = ANY(ARRAY[1, 2, 3, 4, 5])
请注意,这需要 id 列表由 int 组成,因此如果您有字符串列表,请务必先转换它们。
