无法从 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);
最佳答案
你必须学习 javascript/nodejs 和事件编程。
query.on('row', function() {/*CODE*/})
意思是:“读取一行时,执行CODE”。
这是异步的;所以 query.on() 注册事件,并返回。
所以当 console.log(rows)
被调用时,rows 仍然是空的,因为查询时还没有触发 'row' 事件。
您应该尝试将 'console.log(rows)' 放在 query.on('end') 事件处理程序的主体中。
在代码的任何地方,你也应该写一些console.log
。你会看到异步的东西。
关于node.js - 使用 node-postgres 从 SELECT 返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17441495/