使用node-postgres查询postgres数据库

时间:2015-12-12 06:03:37

标签: node.js postgresql express node-postgres

每次查询数据库时是否需要使用pg.connect()?在查看githhub页面和wiki之后,这些示例在pg.connect回调中显示了一个查询(这些注释来自github示例,我没有写它们)

//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 20 (also configurable)
pg.connect(conString, function(err, client, done) {
  if(err) {
    return console.error('error fetching client from pool', err);
  }
  client.query('SELECT $1::int AS number', ['1'], function(err, result) {
    //call `done()` to release the client back to the pool
    done();

    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].number);
    //output: 1
  });
});

评论很混乱,因为听起来pg.connect()正在为每次调用创建一个新的客户端池,这显然效率低下。我在文档中看到了创建客户端的其他示例,但我想使用客户端池。

1 个答案:

答案 0 :(得分:2)

Yea pg.connect是推荐的做事方式。如github页面中所述:https://github.com/brianc/node-postgres。它不是为每个请求创建一个池,而是一个新的请求将创建一个“池”,所有后续查询都会添加到该连接,直到超时,30秒。 //它将保持空闲连接打开(可配置)30秒因此,当应用程序未被使用时,没有连接,但是一旦您每秒获得一些查询,它们都是在那个连接上排队。可以更改超时和排队的金额。