SQLite is a self-contained database engine that requires no server to run (for MySQL, Oracle we require a Database Server). SQLite is most popular in developing mobile apps and it is considered as most widely deployed database engine in the world.
NodeJS SQLite Tutorial
In this tutorial, I am going to explain how to use SQLite with NodeJS. Let’s create a project named “node-sqlite” and in that create a package file as “package.json”. Paste the following code in it.
{<br>
"name": "node-sqlite",<br>
"version": "1.0.1",<br>
"dependencies": {<br>
"sqlite3": "~2.2.3"<br>
}<br>
}<br>
Install the project by typing “npm install” in the terminal or command prompt. It will install all dependencies and make your project ready to work.
SQLite Database Schema Setup
SQLite is a transactional database engine, which means you can run DDL and DML queries of SQL. DDL queries deal with the creation of database, tables, view etc. whereas DML queries are responsible for CRUD operation (insert, delete, update, etc.). Here is the code to create an SQLite database and performing SQL operations.
var sqlite3 = require('sqlite3').verbose();<br>
var db = new sqlite3.Database('mydb.db');<br>
var check;<br>
db.serialize(function() {
var stmt = db.prepare("INSERT INTO user_info VALUES (?)");<br>
for (var i = 0; i < 10; i++) {<br>
stmt.run("Ipsum " + i);<br>
}<br>
stmt.finalize();
db.each(“SELECT rowid AS id, info FROM user_info”, function(err, row) {
console.log(row.id + “: ” + row.info);
});
});
To run and analyse the code, type node filename.js (in my case app.js) and see whether it creates a “mydb.sql” file in your folder or not. This code will create a table in the database and add some numbers and displays them in the console.
SQLite Queries using NodeJS
To perform the SELECT query you should use the .all function and for other operations such as DELETE, UPDATE, INSERT you should use the .run function. Here have a look at simple code.
//Load modules<br>
var sqlite3 = require('sqlite3').verbose();<br>
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”);
db.run("UPDATE table_name where condition");<br>