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

passing many arguments to one placeholder of django cursor (placeholer in IN)

我的意思是这样的:

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)

用占位符似乎很难实现。

更新答案 对不起,旧的答案。这应该可以如您所愿,但可能不是最佳解决方案。我尝试了两者,params 作为字符串列表和整数列表。

from django.db import connection

params = [1, 2, 3, '4', '5']
placeholders = ('%s,'*len(params)).rstrip(',')  # Having a comma at the end will give a syntax error

with connection.cursor() as cursor:
    cursor.execute('SELECT * FROM mytable where id IN ({})'.format(placeholders), params)
    #  Use the cursor here 

结束更新的答案


在 SQL 中 IN 的值需要是逗号分隔的列表

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

因此,假设 params 是可迭代的,对您来说最简单的方法是

from django.db import connection
with connection.cursor() as cursor:
    cursor.execute('SELECT * FROM mytable where id IN (%s)', [', '.join(params)])  

连接会将您的可迭代参数转换为逗号分隔的字符串,然后替换 %s。

通常您会希望对查询参数进行转义。甚至你存储的数据也应该被转义。

编辑: 另请注意,我已将您的光标移动到 with 块中。您应该始终关闭您的连接。 Read up more here.

解决方法很简单:

c.execute('select * from mytable where id in (%s)' % (','.join(params),))

查看类似主题: imploding a list for use in a python MySQLDB IN clause

你不能为此使用 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 组成,因此如果您有字符串列表,请务必先转换它们。