python - 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)
解决方案
我发现您分享的片段存在一些问题
- postgresql 中的删除语法是
delete from <tablename> where ...
- 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
推荐阅读
- python-3.x - Python 相同的代码在 IDLE 和 Komodo 中给出不同的输出编辑
- c++ - 有没有办法检测一个圆圈是否连接到另一个圆圈与opencv中的一条线?
- c++ - 我的代码覆盖自身时遇到问题,我不知道为什么
- oracle - ORACLE DB 24 小时记录计数
- html - 为什么我的用于使徽标居中的 CSS 代码不起作用?
- javascript - 创建一个动态表,添加依赖于 JQuery 或 JavaScript 中的数据的列和行
- reactjs - ReactJS 基于认证的展示组件
- docker - 如何在 Kubernetes 中分离应用程序和数据同步实现?
- html - 如何在页脚中居中社交媒体图标?
- imodeljs - 我可以使用自己的服务来构建 imodel 显示程序吗?