简体   繁体   English

使用node-postgres从SELECT返回结果

[英]Returning result from SELECT with node-postgres

Having trouble getting results back from SELECT queries in node-postgres. 无法从node-postgres中的SELECT查询中获取结果。 Now rows are empty at the end of the codeblock. 现在,代码块末尾的行为空。 This select just returns a next value from a sequence in POSTGRESQL. 此选择只返回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(或任何其他数据库模块到节点)可能知道修复?

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);

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*/ })表示:“当读取一行时,执行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)调用So when console.log(rows) ,行仍为空,因为在查询时尚未触发“row”事件。

You should try putting 'console.log(rows)' in the body of the query.on('end') event handler. 您应该尝试在query.on('end')事件处理程序的主体中放入'console.log(rows)'。

Everywhere in the code, also, you should write some console.log . 在代码中的任何地方,你也应该编写一些console.log You'll see the asynchronous thing. 你会看到异步的东西。

If we did not call the result.addRow() method, the rows array would be empty in the end event. 如果我们没有调用result.addRow()方法,则rows数组在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();
});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM