node.js - sqlite3 读取表中的所有记录并返回 [英] node.js - sqlite3 read all records in table and return

查看:139
本文介绍了node.js - sqlite3 读取表中的所有记录并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取 sqlite3 表中的所有记录并通过回调返回它们.但似乎尽管使用了序列化,这些调用仍然是异步的.这是我的代码:

I'm trying to read all records in a sqlite3 table and return them via callback. But it seems that despite using serialize these calls are still ASYNC. Here is my code:

var readRecordsFromMediaTable = function(callback){

    var db = new sqlite3.Database(file, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);

    var allRecords = [];

    db.serialize(function() {

        db.each("SELECT * FROM MediaTable", function(err, row) {

            myLib.generateLog(levelDebug, util.inspect(row));
            allRecords.push(row);

        }

        callback(allRecords);
        db.close();

    });

}

当回调被触发时,数组会打印[]".

When the callback gets fired the array prints '[]'.

是否还有另一个调用(而不是 db.each)可以一次性给我所有行.我不需要在这里遍历每一行.

Is there another call that I can make (instead of db.each) that will give me all rows in one shot. I have no need for iterating through each row here.

如果没有,我如何读取所有记录,然后才调用带有结果的回调?

If there isn't, how do I read all records and only then call the callback with results?

推荐答案

我找到了这个问题的答案.任何正在寻找的人都在这里:

I was able to find answer to this question. Here it is for anyone who is looking:

var sqlite3 = require("sqlite3").verbose();

var readRecordsFromMediaTable = function(callback){

    var db = new sqlite3.Database(file, sqlite3.OPEN_READONLY);

    db.serialize(function() {

        db.all("SELECT * FROM MediaTable", function(err, allRows) {

            if(err != null){
                console.log(err);
                callback(err);
            }

            console.log(util.inspect(allRows));

            callback(allRows);
            db.close();

        });


    });

}

这篇关于node.js - sqlite3 读取表中的所有记录并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆