Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SQLite3 have prepared statements in Node.js?

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 a .each function where the rows are called back. Anyone been able to do this or have links to resources, cause I can sure as hell unable to find any.

like image 467
lzc Avatar asked Mar 02 '15 05:03

lzc


2 Answers

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"
});
like image 144
c.hill Avatar answered Sep 27 '22 21:09

c.hill


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);
like image 31
Bernardo Ramos Avatar answered Sep 27 '22 22:09

Bernardo Ramos