Open In App

How to connect sqlite3 database using Node.js ?

Last Updated : 22 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to connect the sqlite3 database using nodejs. So for this, we are going to use the Database function which is available in sqlite3.

SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world. It is an in-process library and its code is publicly available. It is free for use for any purpose, commercial or private. It is basically an embedded SQL database engine. Ordinary disk files can be easily read and written by SQLite because it does not have any separate server like SQL. The SQLite database file format is cross-platform so that anyone can easily copy a database between 32-bit and 64-bit systems. Due to all these features, it is a popular choice as an Application File Format.

Let’s understand How to connect sqlite3 database using node.js. Below is the step by step implementation:

Step 1: Setting up of the NPM package of the project :

npm init -y

Step 2: Installing Dependencies :

npm install express sqlite3

Project structure: It will look like the following.

Step 3:  Here, we created a basic express server which renders GeeksforGeeks.

index.js




const express = require('express');
const app = express();
     
app.get('/' , (req , res)=>{
    res.send("GeeksforGeeks");
})
    
app.listen(4000 , ()=>{
    console.log("server started");
})


Output:

Step 4:  Importing ‘sqlite3’ into our project, there are lots of features in sqlite3 module.

Syntax:

const sqlite3 = require('sqlite3');

Here we are going to use Database method which is available in sqlite3 which helps us to connect with database.

index.js




const express = require('express');
const app = express();
const sqlite3 = require('sqlite3');
  
// Connecting Database
let db = new sqlite3.Database(":memory:" , (err) => {
    if(err)
    {
        console.log("Error Occurred - " + err.message);
    }
    else
    {
        console.log("DataBase Connected");
    }
})
  
  
app.get("/" , (req , res) => {
    res.send("GeeksforGeeks");
})
  
// Server Running
app.listen(4000 , () => {
    console.log("Server started");
})


Step to Run Server: Run the server using the following command from the root directory of the project:

node index.js

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads