querying postgres db with node-postgres

2019-08-09 11:15发布

Do I need to use pg.connect() every time I query the database? After looking over the githhub page and wiki, the examples show a query inside the pg.connect callback like this (the comments are from the github example, i did not write them)

//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
  });
});

The comments are confusing because it sounds like pg.connect() is creating a new client pool with each call which would obviously be inefficient. I have seen other examples in the documentation that create a client, but I want to use the client pool.

1条回答
仙女界的扛把子
2楼-- · 2019-08-09 11:52

Yea pg.connect is the recommended way of doing things. as stated in the github page: https://github.com/brianc/node-postgres. Its not creating a pool for each request, rather a new request will create a 'pool' and all subsequent queries are added to that connection, until the time-out, 30 seconds. //it will keep idle connections open for a (configurable) 30 seconds So when the app isn't being used there is no connection, but once you are getting a few queries every second, they are all queued on that connection. the time out and amount queued can be changed.

查看更多
登录 后发表回答