Node.js and SQLite3

Node.js and SQLite3

本文关键字:SQLite3 and js Node      更新时间:2023-09-26

我想创建将为我的移动应用程序返回数据的Web服务器。我使用 Node.js 用于服务器,将 SQLite3 用于数据库。我创建了必须从 sql 返回数据的方法,但我不知道如何正确执行此操作。因为我知道 SQLite lib 中的所有方法都是异步的,所以我不知道如何对 DB 进行同步请求。我尝试了这种方式:

app.get('/getAllLeagues',function (req, res) {
  console.log("get")
  var obj = db.all("SELECT name FROM Leagues")
})

但似乎 obj 仍然与 db 对象相同

我假设您的应用程序是快速服务器实例或类似实例。数据库查询函数采用回调函数,一旦查询的行准备就绪或发现错误,就会调用该函数。

app.get('/getAllLeagues',function (req, res) {
  console.log("get")
  var obj = db.all("SELECT name FROM Leagues",
    function(err, rows) {
        res.type('json');
        res.send(rows);
    });
});

为简单起见,没有错误处理。最好尝试一下..捕获类似的请求,以避免在找不到数据库或表时使应用崩溃。