Skip to content

Instantly share code, notes, and snippets.

@TravelingTechGuy
Created August 1, 2011 05:01
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TravelingTechGuy/1117596 to your computer and use it in GitHub Desktop.
Save TravelingTechGuy/1117596 to your computer and use it in GitHub Desktop.
Using SQLite from Node.js
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('guy.sqlite'); //':memory:'
db.serialize(function() {
db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='lorem'", function(error, row) {
if (row !== undefined) {
console.log("table exists. cleaning existing records");
db.run("DELETE FROM lorem", function(error) {
if (error)
console.log(error);
});
}
else {
console.log("creating table")
db.run("CREATE TABLE lorem (info TEXT)", function(error) {
if (error.message.indexOf("already exists") != -1) {
console.log(error);
}
});
}
});
var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
for (var i = 0; i < 10; i++) {
stmt.run("Ipsum " + i, function(error) {
if (error)
console.log(error);
});
}
stmt.finalize();
db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
console.log(row.id + ": " + row.info);
});
//db.close();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment