将许多参数传递给 django 游标的一个占位符(IN 中的占位符)

Sła*_*art 5 python sql django placeholder

我的意思是这样的:

from django.db import connection
cursor=connection.cursor()
cursor.execute('SELECT * FROM mytable where id IN (%s)', [params])
Run Code Online (Sandbox Code Playgroud)

参数不能只是可迭代的——它不起作用。由于数据库处理程序转义值,因此也不能采用 CSV 格式。

如何在 中使用占位符IN


CSV 是错误的,我的意思是params=['1','2','3','4','5']

c.execute('select * from mytable where id in (%s)', [','.join(params)])
Run Code Online (Sandbox Code Playgroud)

将产生:

select * from mytable where id  in ('1,2,3,4,5')
Run Code Online (Sandbox Code Playgroud)

但正确的sql是:

select * from mytable where id  in (1,2,3,4,5)
Run Code Online (Sandbox Code Playgroud)

而且用占位符似乎很难实现。

Bjö*_*son 4

你不能使用IN它,因为实际上, in 需要一个整数序列,但 ORM 将列表转换为 an ARRAY,如果你使用,join你最终会得到一个字符串。

解决方案是使用等效的ANY. 格式略有不同,但这应该适合您:

c.execute('select * from mytable where id = ANY(%s)', [params])
Run Code Online (Sandbox Code Playgroud)

给定params = [1, 2, 3, 4, 5],生成的 SQL 将是:

SELECT * FROM mytable where id = ANY(ARRAY[1, 2, 3, 4, 5])
Run Code Online (Sandbox Code Playgroud)

请注意,这要求 id 列表由整数组成,因此如果您有字符串列表,请务必先将它们转换。