使用node-postgres从SELECT返回结果

无法从node-postgres中的SELECT查询中获取结果。 现在,在代码块的末尾,行是空的。 这个select只是从POSTGRESQL的一个序列中返回下一个值。 我知道你不能从callback中获取结果,但是在这里有没有人使用过node-postgres(或者任何其他数据库模块到节点)来解决这个问题?

client.connect(); var query = client.query("SELECT nextval(\'idgenerator\');"); var rows = []; query.on('row', function(row, res) { rows.push(row); }); query.on('end', function(result) { console.log(result.rowCount + ' rows were received'); }); //client.end(); console.log(rows); 

你将不得不学习javascript / nodejs和事件编程。

query.on('row', function() { /*CODE*/ })表示:“读取一行时,执行CODE”。

这是asynchronous的; 所以query.on()注册事件,并返回。

So when console.log(rows)调用So when console.log(rows) ,行仍然是空的,因为在查询中没有触发'row'事件。

您应该尝试在query.on('end')事件处理程序的主体中放置“console.log(rows)”。

在代码中的任何地方,你也应该写一些console.log 。 你会看到asynchronous的东西。

如果我们没有调用result.addRow()方法,则在结束事件中rows数组将为空。

 var query = client.query("SELECT firstname, lastname FROM emps ORDER BY lastname, firstname"); query.on("row", function (row, result) { result.addRow(row); }); query.on("end", function (result) { console.log(JSON.stringify(result.rows, null, " ")); client.end(); }); 

参考: http : //nodeexamples.com/2012/09/21/connecting-to-a-postgresql-database-from-node-js-using-the-pg-module/