postgresql 使用 node-postgres 从 SELECT 返回结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17441495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning result from SELECT with node-postgres
提问by magnudae
Having trouble getting results back from SELECT queries in node-postgres. Now rows are empty at the end of the codeblock. This select just returns a next value from a sequence in POSTGRESQL. I know that you can not retrieve results from callback, but are there anyone here who have used node-postgres(or any other database modules to node) that might know a fix?
从 node-postgres 中的 SELECT 查询获取结果时遇到问题。现在代码块末尾的行是空的。此选择仅从 POSTGRESQL 中的序列返回下一个值。我知道你不能从回调中检索结果,但是这里有没有人使用过 node-postgres(或任何其他数据库模块到 node)可能知道修复?
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);
采纳答案by Drasill
You'll have to learn javascript / nodejs, and event programming.
您必须学习 javascript / nodejs 和事件编程。
query.on('row', function() { /*CODE*/ })
means : "when a row is read, execute CODE".
query.on('row', function() { /*CODE*/ })
意思是:“读取一行时,执行代码”。
This is asynchronous; so query.on() register the event, and returns.
这是异步的;所以 query.on() 注册事件,然后返回。
So when console.log(rows)
is called, rows is still empty, because no 'row' event has been triggered on query, yet.
So when console.log(rows)
被调用时,rows 仍然是空的,因为查询时还没有触发 'row' 事件。
You should try putting 'console.log(rows)' in the body of the query.on('end') event handler.
您应该尝试将 'console.log(rows)' 放在 query.on('end') 事件处理程序的主体中。
Everywhere in the code, also, you should write some console.log
. You'll seethe asynchronous thing.
在代码的任何地方,你也应该写一些console.log
. 你会看到异步的东西。
回答by abdulwadood
If we did not call the result.addRow() method, the rows array would be empty in the end event.
如果我们不调用 result.addRow() 方法,则行数组在 end 事件中将为空。
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/