Asked 7 years ago
7 Feb 2017
Views 1989
yogi

yogi posted

how to connect SQLite in Node JS

trying to connect Node Js with SQLite

but don't know where to start

so how to connect SQLite in Node JS ?
Rasi

Rasi
answered Nov 30 '-1 00:00

sqlite 3 is good option to use [b] SQLite [/b ] with Node JS

sqlite 3 give you to option to control execution flow by serialize function

db.serialize will allow to run first and their inner serialize function will start to run

db.serialize(function() {
  // Queries scheduled here will be run first 
  db.serialize(function() {
    // Queries scheduled here will still be run second.
  });
 
});



you can fetch each record by each function form SQLite database


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


close the SQLite connection when you done with it

 db.close();

shyam

shyam
answered Nov 30 '-1 00:00


you can connect with memory by using following code


var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(":memory:");
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

download the sqlite3 module for Node JS


npm install sqlite3


Lets connect Node to MySQL
sqlite3 module provide good set of library to get connection to SQLite

include sqlite3module


var sqlite3 = require('sqlite3')


Database is used to construct the connection

var db = new sqlite3.Database(file);


where file is var file="D:/software/sqllite/example.sqlite";
it can be any SQLite file with accessible path

all function return result set for SQLite


db.all("SELECT id, name   FROM employee", function(err, employee){
    if(err !== null){
        console.log(err);
    }
    else{
        console.log(employee);
    }
});


it give all employee list in array format

lets use dynamic value


var id ='12\n1';
db.all("SELECT id, name   FROM employee where id=?",(id), function(err, employee){
    if(err !== null){
        console.log(err);
    }
    else{
        console.log(employee);
    }
});


lets use the prepare statement

//delete query with prepare statement
var statement = db.prepare("DELETE FROM employee WHERE id = ?", (id));
statement.run();
statement.finalize();


Github
Post Answer