postgres 使用 python 删除批量查询

postgres delete query for batch using python

我想在 postgres 中使用 python 进行批量删除,我的 where 子句有多个列来获取正确的记录。

例如: 对于 One 记录,我 运行 这个 删除 company_id='123' 和 product_id=1;

的产品

我对多条记录进行了尝试,但出现此错误

the query contains more than one '%s' placeholder

query = delete products where company_id='%s' and product_id=%s; 
values =[(1,2),(3,4)]
psycopg2.extras.execute_values(self.cursor, delete_query, values)

我发现您分享的代码段存在一些问题

  1. postgresql 中的删除语法是 delete from <tablename> where ...
  2. company_id 似乎是一个字符串,但在值中它表示为一个整数。

您可以执行多个查询来删除记录,也可以传递值列表以与复合字段进行比较 (company_id, product_id) 并使用 execute_values

假设 company_id 是文本并且您的值列表包含字符串

多个查询:

stmt = "delete from products where company_id = %s and product_id = %s"
cur.execute('begin')
try:
    for cid, pid in values:
      cur.execute(stmt, (cid, pid))
    cur.execute('commit')
    # do other things
except:
    cur.execute('rollback')
    # do other things to handle this exception

一个查询 + execute_values

from postgresql.extras import execute_values

stmt = "delete from products where (company_id, product_id) IN (%s)"
execute_values(cur, stmt, values)

psycopg2.extras documentation page 包含许多有用的功能,包括 execute_values

的文档

您正在向每个 %s 发送一个元组,而不是单个值。

应该这样使用:

参考: https://www.psycopg.org/docs/extras.html?highlight=uuid

>>> execute_values(cur,
... """UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1)
... WHERE test.id = data.id""",
... [(1, 20), (4, 50)])

所以在你的情况下,它需要遵循这些原则。看看他们如何引用数据。

    ... """DELETE products USING (VALUES %s) AS data (companyId, productId)
    ... WHERE company_id = data.companyId  and product_id = data.productId """,
    ... [(1, 20), (4, 50)])