2017-10-08 226 views
0

我做了postgres助手,用于连接数据库并执行查询。代码:NodeJS Postgres助手 - 释放连接

var pg = require('pg'); 
 
var dbConn = require('../config.json').dbConn; 
 
var pool = new pg.Pool(dbConn); 
 

 
var status = { 
 
    "OK": 0, 
 
    "ERROR": 1 
 
}; 
 
var message = { 
 
    "success": "success", 
 
    "error": "error", 
 
    "databaseError": "Database error" 
 
}; 
 

 
var helper = { 
 
    query: function (query, params, success, error) { 
 
     pool.connect(function (err, client, done) { 
 
      if (err) { 
 
       error({ 
 
        status: status.ERROR, 
 
        message: message.databaseError, 
 
        data: err 
 
       }); 
 
       return; 
 
      } 
 
      client.query(query, params, function (err, result) { 
 
       //call `done()` to release the client back to the pool 
 
       done(); 
 

 
       if (err) { 
 
        error({ 
 
         status: status.ERROR, 
 
         message: message.databaseError, 
 
         data: err 
 
        }); 
 
        return; 
 
       } 
 
       success({ 
 
        status: status.OK, 
 
        message: message.success, 
 
        result: result 
 
       }); 
 
      }); 
 
     }); 
 
    } 
 
}; 
 

 
module.exports = helper;

它不具有逻辑查询执行后释放连接。所以过了一段时间,我得到数据库错误:“客户太多...” 有人可以告诉我怎么做吗?一旦我尝试了一些东西(要调用close()或release()函数),但它打破了连接,并且我无法发出新的请求,直到我重新启动应用程序。

+0

要避免连接问题干脆,检查出[PG -promise](https://github.com/vitaly-t/pg-promise);) –

回答

0

你这样做的方式,你没有充分利用池,而是每次使用助手时都会创建池。如果您正在使用事务,你应该看看会照顾大多数的pool.query便捷的方法你想要什么:

const { Pool } = require('pg') 

const pool = new Pool() 

pool.query('SELECT * FROM users WHERE id = $1', [1], (err, res) => { 
    if (err) { 
    throw err 
    } 

    console.log('user:', res.rows[0]) 
}) 

https://node-postgres.com/features/pooling#single-query