使用 node-postgres 查询 postgres 数据库

querying postgres db with 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 ::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() 正在为每次调用创建一个新的客户端池,这显然是低效的。我在文档中看到了创建客户端的其他示例,但我想使用客户端池。

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