【发布时间】:2013-04-13 23:12:44
【问题描述】:
我在我的应用程序中使用node-postgres。 我想知道我想遵循的最佳做法以确保稳定的连接。
以下是我现在使用的代码,
exports.getAll = function (args, callback) {
helper.client = new pg.Client('tcp://postgres:system6:5432@192.168.143.11/abc_dev');
helper.client.connect();
helper.client.query('select count(1) as total_records from facilities', function(err,response){
helper.client.query('select * ,'+response.rows[0].total_records+' as total_records from facilities',
function(err,response){
callback(response);
helper.client.end.bind(helper.client);
});
});
};
正如您在代码中看到的,我为每个请求连接数据库,并在查询执行后断开连接。我还有一个想法,我只能在全局范围内连接数据库一次并使用打开的连接执行查询。代码看起来像
helper.client = new pg.Client('tcp://postgres:system6:5432@192.168.143.11/abc_dev');
helper.client.connect();
exports.getAll = function (args, callback) {
helper.client.query('select count(1) as total_records from facilities', function(err,response){
helper.client.query('select * ,'+response.rows[0].total_records+' as total_records from facilities',
function(err,response){
callback(response);
});
});
};
在这里,连接永远不会结束。据我所知,我无法决定哪一个是最好的。 请提出建议。
谢谢..
【问题讨论】:
-
非常有趣的问题。据我所知,请求范围的连接在大多数语言中都很流行。但是,我不确定它是否与 Node 相同。
标签: node.js node-postgres