使用来自 Nodejs Postgres 查询的数据 [重复]

Posted

技术标签:

【中文标题】使用来自 Nodejs Postgres 查询的数据 [重复]【英文标题】:Using data from a Nodejs Postgres query [duplicate] 【发布时间】:2015-09-23 01:07:26 【问题描述】:

谁能给我看一个将 Nodejs 中的 postgres 查询结果传递给另一个函数的示例?

【问题讨论】:

我确定google 可以。 用pg-promise将结果作为promise请求,然后将返回的promise传递给你的函数。 【参考方案1】:

我有一个config.json 文件,用于存储我的配置。

var pg = require('pg')
,q = require('q')
,config = require('custom-modules/config.json')
conString = 'postgres://'+ config.pg.admun +':' + config.pg.admpw + '@' + config.pg.host + ':' + config.pg.port + '/' + config.pg.defdb;

function runSQL (sqlStatement) 
    var deferred = q.defer(); 
    var results = [];

    // Get a Postgres client from the connection pool
    pg.connect(conString, function(err, client, done) 


        // SQL Query > Select Data
        var query = client.query(sqlStatement, function(err, res) 
            if(err) console.log(err);
            deferred.resolve(res);
        );


        // After all data is returned, close connection and return results
        query.on('end', function() 
            client.end();
            deferred.resolve(results);
        );

        // Handle Errors
        if(err) 
          console.log(err);
        

    );

    return deferred.promise;
;

现在你可以像这样运行函数了:

runSQL("SELECT * FROM tablename").then(function(res) 
// here you have access to the result of the query... with "res".
console.log(res);
);

【讨论】:

或者,你可以使用pg-promise ;)

以上是关于使用来自 Nodejs Postgres 查询的数据 [重复]的主要内容,如果未能解决你的问题,请参考以下文章