使用node-postgres查询postgres db [英] querying postgres db with node-postgres

查看:118
本文介绍了使用node-postgres查询postgres db的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次查询数据库都需要使用pg.connect()吗?在查看了githhub页面和wiki之后,这些示例显示了pg.connect回调内部的查询,如下所示(注释来自github示例,我没有编写)

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

注释令人困惑,因为听起来pg.connect()正在与每个对象创建新的客户端池通话显然效率低下。我已经在创建客户端的文档中看到了其他示例,但是我想使用客户端池。

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。推荐的连接方式是做事。如github页面中所述: https://github.com/brianc/node-postgres 。它不会为每个请求创建一个池,而是一个新请求将创建一个池,并且所有后续查询都将添加到该连接中,直到超时30秒。 //它将保持空闲连接30秒(可配置)的打开状态(可配置)。因此,当不使用该应用程序时,没有连接,但是一旦您每秒收到几个查询,它们便全部在该连接上排队。超时和排队的数量可以更改。

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.

这篇关于使用node-postgres查询postgres db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆