首页 > 解决方案 > postgres使用python批量删除查询

问题描述

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

例如:对于一个记录,我运行此删除产品 where company_id='123' and product_id=1;

我尝试了多条记录,但收到此错误

查询包含多个“%s”占位符

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)

标签: pythonpostgresqlpsycopg2

解决方案


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

  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

一个查询 + 执行值

from postgresql.extras import execute_values

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

psycopg2.extras 文档页面包含许多有用的功能,包括用于execute_values


推荐阅读