【问题标题】:pg-promise number of updated rowspg-promise 更新行数
【发布时间】:2017-11-29 11:40:42
【问题描述】:

我正在使用 pg-promise NodeJS 模块。在某些时候,我正在更新我的数据库表之一。我想知道查询更新了多少行,可以吗?

以下是我的部分代码:

var queryText = "UPDATE public.mytable SET whatever = $1 WHERE criteria1=$2 AND criteria2=$3;",
    queryParam = [
      value1,
      value2,
      value3
    ];

    postgres.none(queryText, queryParam)
    .then((value) => {
      // how can I know at this point how many rows have been updated
      resolve(result);

    })
    .catch(err => {
      // it doesn't go here when zero row has been updated
      reject(err);
    });

谢谢!

【问题讨论】:

    标签: node.js pg-promise


    【解决方案1】:

    我是pg-promise 的作者。为了访问高级查询结果详细信息,您需要通过方法result 执行查询。在您的情况下,您将访问属性 rowCount:

    db.result(query, values, r => r.rowCount)
        .then(count => {
           // count = number of rows affected (updated or deleted) by the query
        })
        .catch(error => {
        });
    

    附:您不需要在.then 中使用resolve(result) 或在.catch 中使用reject(err),因为pg-promise 的所有查询方法都已返回promise。

    更新

    较新的 ES7 语法:

    const {rowCount} = await db.result(query, values);
    

    【讨论】:

    • 如果你在 async 函数中,你也可以做例如let result = await db.result('DELETE FROM mytable WHERE criteria1 = $1', ['foo'])
    • @DaveGray 当一个人从 ES6 转移到 ES7 语法时,这是不言而喻的。至少您可以正确使用该示例,使用转换 r => r.rowCount 参数,否则该示例将无法正常工作。
    • 你是对的,如果不做let result = await db.result('DELETE FROM mytable WHERE criteria1 = $1', ['foo'], r => r.rowCount),这不是一个完全的替代品 - 向 OP 道歉;在我的用例中,我想查看整个结果对象。感谢图书馆,它为我节省了很多时间!
    • 添加了 ES7 示例。
    • @PirateApp 你不能。 Postgres 只能报告有多少行受到影响/修改,没有任何细节。
    猜你喜欢
    • 2017-04-03
    • 2018-04-15
    • 2020-06-12
    • 1970-01-01
    • 2020-10-21
    • 2021-07-03
    • 2021-09-27
    • 1970-01-01
    • 2020-11-29
    相关资源
    最近更新 更多