Does SQLite3 have prepared statements in Node.js?

前端 未结 2 1135
情书的邮戳
情书的邮戳 2021-02-07 07:35

From the npm docs, only visible prepared statements are for insert. Does these prepared statement work for Select, update, and delete?

I tried for select, there isn\'t

2条回答
  •  你的背包
    2021-02-07 08:35

    Yes, prepared statements are supported.

    With 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();
      });
    
    });
    

    With 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);
    

提交回复
热议问题