How to read a sqlite3 database, using node js, synchronously?

青春壹個敷衍的年華 提交于 2021-01-18 04:57:07

问题


exports.allProbes = function() {
    var rows = db.all("SELECT * FROM probes;");
    return rows;
};

main:
var json_values = allProbes();

Is it possible to do something like that? I mean, without using a callback function: just, read data (sync mode) from the db. and return a json formatted output?

Thanks.


回答1:


You will not be able to do that with sqlite3. With sqlite3 module the only available mode of operation is asynchronous execution, and you will have to use a callback. Eg.

exports.allProbes = function(callback) {
    db.all("SELECT * FROM probes;", function(err, all) {
        callback(err, all);  
    });
};

Then in your code:

var json_values;

allProbes(function(err, all) {
    json_values = all;
});

Check sqlite3 API Docs.




回答2:


There are a few npm packages such as better-sqlite3 and sqlite-sync that allow for synchronous SQLite queries. Here's an example:

var sqlite = require("better-sqlite3");
var db = new sqlite("example.db");

var rows = db.prepare("SELECT * FROM probes").all();
console.log(rows);



回答3:


You have to install sql.js with npm install --save sql.js

Rest follow the below steps :

var fs = require('fs');    
var sql = require('sql.js');    
var bfr = fs.readFileSync('/tmp/db.sqlite');

var db = new sql.Database(bfr);
db.each('SELECT * FROM test', function (row) {

  console.log(row);

});

More details you can get on the below this link : https://discuss.atom.io/t/how-to-access-a-local-db-on-windows-through-electron/22400/13



来源:https://stackoverflow.com/questions/15575914/how-to-read-a-sqlite3-database-using-node-js-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!