【问题标题】:nodejs + pg do crud with callbacknodejs + pg 用回调做 crud
【发布时间】:2015-10-23 14:31:51
【问题描述】:

我正在学习 nodejs express + pg。如果我想做crud,我应该使用第一种方法还是第二种方法? 有什么区别吗?

var query = "SELECT EXISTS(SELECT * FROM table WHERE user_email = '" + user_email + "')";

// 1
var result = dbClient.query(query);
console.log(result);
console.log(result._result.rowCount);

// 2
dbClient.query(query, function(err, result) {
  console.log(result);
  console.log(result.rows[0].exists);
});

连接

...
var conString = "postgres://db_admin:pwd@localhost/databasename";
var dbClient = new pg.Client(conString);
dbClient.connect();

【问题讨论】:

    标签: node.js postgresql express


    【解决方案1】:

    我会选择:

    // 2
    dbClient.query(query, function(err, result) {
      if (err) {
        // do something with err
      }
      else{
        console.log(result);
        console.log(result.rows[0].exists);
      }
    });
    

    或者你可以:

    如文档所示:

        var query = client.query('select name from person');
        var rows = [];
        query.on('row', function(row) {
          //fired once for each row returned
          rows.push(row);
        });
        query.on('end', function(result) {
          //fired once and only once, after the last row has been returned and after all 'row' events are emitted
          //in this example, the 'rows' array now contains an ordered set of all the rows which we received from postgres
          console.log(result.rowCount + ' rows were received');
        })
    

    但是,当您遇到深度嵌套的回调时,我建议您考虑使用 Promise。

    见:

    【讨论】:

    • @user1775888,链接更新,参考pg-promise ;)
    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多