如何获取 PostgreSQL 中删除的行数?
我正在寻找一种方法来返回 PostgreSQL 中受 DELETE 子句影响的行数。 文档指出;
成功完成后,删除 命令返回命令标签 表格
删除计数
计数是行数 已删除。如果 count 为 0,则没有行 符合条件(这不是 被认为是一个错误)。
如果 DELETE 命令包含 RETURNING 子句,结果将是 类似于 SELECT 语句 包含列和值 在 RETURNING 列表中定义, 计算删除的行 命令。
但我很难找到一个很好的例子。谁能帮我解决这个问题,如何找出删除了多少行?
编辑: 我想提出一个我后来找到的替代方案。它可以在此处找到,在38.5.5下解释。获取结果状态 标题。
I am looking for a way to return the number of rows affected by a DELETE clause in PostgreSQL. The documentation states that;
On successful completion, a DELETE
command returns a command tag of the
formDELETE count
The count is the number of rows
deleted. If count is 0, no rows
matched the condition (this is not
considered an error).If the DELETE command contains a
RETURNING clause, the result will be
similar to that of a SELECT statement
containing the columns and values
defined in the RETURNING list,
computed over the row(s) deleted by
the command.
But I am having trouble finding a good example of it. Can anyone help me with this, how can I find out how many rows were deleted?
EDIT:
I wanted to present an alternative that I have found later. It can be found in here, explained under 38.5.5. Obtaining the Result Status title.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 RETURNING 子句:
之后您只需检查返回的行数。您可以使用 CTE 简化它:
这应该只返回已删除的行数。
You can use
RETURNING
clause:After that you just have to check number of rows returned. You can streamline it with CTE:
This should return just the number of deleted rows.
GET DIAGNOSTICS 用于显示修改/删除的记录数。
示例代码
GET DIAGNOSTICS is used to display number of modified/deleted records.
Sample code
这在 Java 中应该很简单。
请参阅 java.sql.语句。
This should be simple in Java.
See java.sql.Statement.
在使用 psycopg2 的 Python 中,可以使用 rowcount 属性。这是一个示例,用于找出删除了多少行......
in Python using psycopg2, the rowcount attribute can be used. Here is an example to find out how many rows were deleted...
这适用于函数。它也可以与 INSERT 等其他操作一起使用。
This works in functions. It works with other operations like INSERT as well.
您需要
PQcmdTuples
来自libpq
。例如,在 PHP 中,它被包装为pg_affected_rows
。
You need the
PQcmdTuples
function fromlibpq
. Which in PHP for example is wrapped aspg_affected_rows
.