menu

Node and SQLite tutorial

SQLite is a self-contained database engine which require no server to run (for MySQL,Oracle we require Database Server). SQLite is most popular in developing mobile apps and it is consider as most widely deployed database engine in the world.

Download code from Github.

In this tutorial i am going to explain how to use SQLite with Node.js. Let’s create project named as “node-sqlite” and in that create package file as “package.json”. Paste following code in it.

{
  "name": "node-sqlite",
  "version": "1.0.1",
  "dependencies": {
    "sqlite3": "~2.2.3"
  }
}

Install the project by typing “npm install” in terminal or command prompt. It will install all dependencies and make your project ready to work.

NPM INSTALL

SQLite is transaction database engine, it means you can run DDL and DML queries of SQL. DDL queries deal with creation of database, tables, view etc where as DML queries are responsible for CRUD operation (insert,delete,update) etc. Here is a code to create SQLite database and performing SQL operations.

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('mydb.db');
var check;
db.serialize(function() {

  db.run("CREATE TABLE if not exists user_info (info TEXT)");
  var stmt = db.prepare("INSERT INTO user_info VALUES (?)");
  for (var i = 0; i < 10; i++) {
      stmt.run("Ipsum " + i);
  }
  stmt.finalize();

  db.each("SELECT rowid AS id, info FROM user_info", function(err, row) {
      console.log(row.id + ": " + row.info);
  });
});

db.close();

To run and analyse the code, type node filename.js (in my case app.js) and see whether it creates “mydb.sql” file in your folder or not. This code will create table in database and add some numbers and displays it in console.

SQLite output

This is tutorial is for beginners. In further series i will post login-signup system and other useful tutorials about Node.js and SQLite.

SQL Queries using NodeJS:

To perform SELECT query you should use .all function and for other operations such as DELETE, UPDATE, INSERT you should use .run function. Here have a look to simple code.

//Load modules
var sqlite3         =       require('sqlite3').verbose();
var db              =       new sqlite3.Database('./database_name.db');

//Perform SELECT Operation
db.all("SELECT * from blah blah blah where this="+that,function(err,rows){
//rows contain values while errors, well you can figure out.
});

//Perform INSERT operation.
db.run("INSERT into table_name(col1,col2,col3) VALUES (val1,val2,val3)");

//Perform DELETE operation
db.run("DELETE * from table_name where condition");

//Perform UPDATE operation
db.run("UPDATE table_name where condition");

Further reading: