nodejs sqlite 3 "SQLITE_MISUSE: Database handle is closed" db.run 在 db.all 内

nodejs sqlite 3 "SQLITE_MISUSE: Database handle is closed" db.run within db.all

所以我正在尝试以下操作:

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('MyDB.db');

console.log("Initializing...")
var MyGUID = "d49dfb07-7ac9-42e7-a355-2707209baea5";
db.serialize(function() {
    db.all("SELECT Name, Status FROM MyTable WHERE MyGUID = ? ", [MyGUID], function(err, rows) {
        console.log(rows);
        db.run("UPDATE MyTable SET readOnly = 0 WHERE MyGUID = 'd49dfb07-7ac9-42e7-a355-2707209baea5'", "", function(err) {
            console.log(err);
        });
    }); 
});

db.close();

这导致“SQLITE_MISUSE:数据库句柄已关闭” 显然我不能 运行 db.all 回调中的 UPDATE 查询。但为什么会这样?

您应该将第二个查询作为参数传递给 db.serialize()。然后它将等待它完成,然后返回并允许 db.close() 到 运行.

db.serialize(function() {
  db.all("SELECT Name, Status FROM MyTable WHERE MyGUID = ? ", [MyGUID], function(err, rows) {
    console.log(rows)
  });
  db.run("UPDATE MyTable SET readOnly = 0 WHERE MyGUID = 'd49dfb07-7ac9-42e7-a355-2707209baea5'", "", function(err) {
    console.log(err);
  });
});