Does SQLite3 have prepared statements in Node.js?

前端 未结 2 1134
情书的邮戳
情书的邮戳 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:33

    According to the node-sqlite3 API documentation, you can use parameters in your SQL queries in several different ways:

    // Directly in the function arguments.
    db.run("UPDATE tbl SET name = ? WHERE id = ?", "bar", 2);
    
    // As an array.
    db.run("UPDATE tbl SET name = ? WHERE id = ?", [ "bar", 2 ]);
    
    // As an object with named parameters.
    db.run("UPDATE tbl SET name = $name WHERE id = $id", {
      $id: 2,
      $name: "bar"
    });
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题