SQLite3是否在Node.js中准备了语​​句?

时间:2015-03-02 05:58:19

标签: sql node.js express sqlite prepared-statement

从npm文档中,只有可见的预处理语句用于插入。这些准备好的语句是否适用于选择,更新和删除?

我尝试选择,没有.each函数来回调行。任何人都可以这样做或者有资源链接,因为我确定无法找到任何资源。

1 个答案:

答案 0 :(得分:7)

是的,支持准备好的陈述。

使用node-sqlite3

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

db.serialize(function() {

  var stmt = db.prepare("INSERT INTO users VALUES (?,?)");
  for (var i = 0; i < 10; i++) {
      stmt.run("user " + i, "email " + i);
  }
  stmt.finalize();

  stmt = db.prepare("SELECT * FROM users WHERE id=?");
  stmt.each(userId, function(err, row) {
      console.log(row.name, row.email);
  }, function(err, count) {
      stmt.finalize();
  });

});

使用better-sqlite3

var Database = require('better-sqlite3');
var db = new Database('foobar.db', options);

var stmt = db.prepare("INSERT INTO users VALUES (?,?)");
for (var i = 0; i < 10; i++) {
    stmt.run("user " + i, "email " + i);
}

var stmt = db.prepare('SELECT * FROM users WHERE id=?');
var row = stmt.get(userId);
console.log(row.name, row.email);