使用node-postgres查询postgres数据库

时间:2022-06-06 01:03:08

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)

每次查询数据库时是否需要使用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
  });
});

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.

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

1 个解决方案

#1


2  

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.

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

#1


2  

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.

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