How to update data in sqlite3 using Node.js ?
Last Updated :
29 Jul, 2024
In this article, we are going to see how to update data in the sqlite3 database using node.js. So for this, we are going to use the run function which is available in sqlite3. This function will help us to run the queries for updating the data.
SQLite is a self-contained, high-reliability, embedded, public-domain, SQL database engine. It is the most used database engine in the world. Let’s understand How to update data in a sqlite3 database using Node.js.
Below is the step by step implementation:
Step 1: Setting up the NPM package of the project using the following command:
npm init -y
Step 2: Install Dependencies using the following command:
npm install express sqlite3
Project structure: It will look like the following.

Step 3: Here, we created a basic express server that renders GeeksforGeeks on the browser screen.
JavaScript
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const PORT = 3000;
// Open a connection to the SQLite database
const db = new sqlite3.Database(':memory:', (err) => {
if (err) {
console.error('Error opening database:', err.message);
} else {
console.log('Connected to the SQLite database.');
createTable(); // Create table when the server starts
}
});
// Create a sample table
function createTable() {
db.run(`CREATE TABLE GFG (ID INTEGER PRIMARY KEY, NAME TEXT)`, (err) => {
if (err) {
console.error('Error creating table:', err.message);
} else {
console.log('Table "GFG" created successfully.');
insertSampleData(); // Insert initial data
}
});
}
// Insert sample data into the table
function insertSampleData() {
const insertQuery = `INSERT INTO GFG (NAME) VALUES ('GeeksforGeeks')`;
db.run(insertQuery, (err) => {
if (err) {
console.error('Error inserting data:', err.message);
} else {
console.log('Sample data inserted successfully.');
}
});
}
// Endpoint to update data in the SQLite database
app.get('/update', (req, res) => {
const updateQuery = `UPDATE GFG SET NAME = "Updated_Name" WHERE ID = 1`;
db.run(updateQuery, function (err) {
if (err) {
console.error('Error updating data:', err.message);
res.status(500).send('Failed to update data.');
} else {
console.log(`Row(s) updated: ${this.changes}`);
res.send('Data updated successfully.');
}
});
});
// Endpoint to get data from the SQLite database
app.get('/data', (req, res) => {
const selectQuery = `SELECT * FROM GFG`;
db.all(selectQuery, [], (err, rows) => {
if (err) {
console.error('Error retrieving data:', err.message);
res.status(500).send('Failed to retrieve data.');
} else {
res.json(rows);
}
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 4: Importing ‘sqlite3’ into our project using the following syntax. There are lots of features in the sqlite3 module.
const sqlite3 = require('sqlite3');
Step 5: Now write a query for updating data in sqlite3.
/* Here GFG is table name */
var updateQuery = 'UPDATE GFG SET NAME = "Updated_Name"';
Step 6: Here we are going to use a Run method which is available in sqlite3 .
JavaScript
const updateQuery = `UPDATE GFG SET NAME = "Updated_Name" WHERE ID = 1`;
db.run(updateQuery, function (err) {
if (err) {
console.error('Error updating data:', err.message);
res.status(500).send('Failed to update data.');
} else {
console.log(`Row(s) updated: ${this.changes}`);
res.send('Data updated successfully.');
}
});
Step 7: Here is the complete index.js.
JavaScript
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const PORT = 3000;
const db = new sqlite3.Database(':memory:', (err) => {
if (err) {
console.error('Error opening database:', err.message);
} else {
console.log('Connected to the SQLite database.');
createTable();
}
});
function createTable() {
db.run(`CREATE TABLE GFG (ID INTEGER PRIMARY KEY, NAME TEXT)`, (err) => {
if (err) {
console.error('Error creating table:', err.message);
} else {
console.log('Table "GFG" created successfully.');
insertSampleData();
}
});
}
function insertSampleData() {
const insertQuery = `INSERT INTO GFG (NAME) VALUES ('GeeksforGeeks')`;
db.run(insertQuery, (err) => {
if (err) {
console.error('Error inserting data:', err.message);
} else {
console.log('Sample data inserted successfully.');
}
});
}
app.get('/update', (req, res) => {
const updateQuery = `UPDATE GFG SET NAME = "Updated_Name" WHERE ID = 1`;
db.run(updateQuery, function (err) {
if (err) {
console.error('Error updating data:', err.message);
res.status(500).send('Failed to update data.');
} else {
console.log(`Row(s) updated: ${this.changes}`);
res.send('Data updated successfully.');
}
});
});
app.get('/data', (req, res) => {
const selectQuery = `SELECT * FROM GFG`;
db.all(selectQuery, [], (err, rows) => {
if (err) {
console.error('Error retrieving data:', err.message);
res.status(500).send('Failed to retrieve data.');
} else {
res.json(rows);
}
});
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step to Run Server: Run the server using the following command from the root directory of the project:
node index.js
Output:
Reference: https://www.npmjs.com/package/sqlite3
Similar Reads
How to Update Data in JSON File using Node?
To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of ContentUsing require() Me
4 min read
How to Create Table in SQLite3 Database using Node.js ?
Creating a table in an SQLite database using Node.js involves several steps, including setting up a connection to the database, defining the table schema, and executing SQL commands to create the table. SQLite is a lightweight and serverless database that is widely used, especially in applications t
3 min read
How to Connect SQLite3 Database using Node.js ?
Connecting SQLite3 database with Node.js involves a few straightforward steps to set up and interact with the database. SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine, making it ideal for small to medium-sized applications. Hereâs how you can connect an
2 min read
How to Post Data in MongoDB Using NodeJS?
In this tutorial, we will go through the process of creating a simple Node.js application that allows us to post data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple
5 min read
How to Insert and Select Data in SQLite3 Database using Node.js ?
Inserting and selecting data in an SQLite3 database using Node.js involves connecting to the database, running SQL queries, and handling the results. SQLite is an excellent choice for small to medium-sized applications due to its simplicity and lightweight nature. This guide will walk you through th
3 min read
How to Update value with put in Express/Node JS?
Express JS provides various HTTP methods to interact with data. Among these methods, the PUT method is commonly used to update existing resources. PrerequisitesNode JS Express JS In this article, we are going to setup the request endpoint on the server side using Express JS and Node JS. This endpoin
2 min read
How to update single and multiple documents in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to Add Data in JSON File using Node.js ?
JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to Make to do List using Nodejs ?
Creating a to-do list application using Node.js involves setting up an Express server, creating RESTful APIs for CRUD operations, and using a database to store tasks. Enhance functionality with features like task prioritization and deadlines. Table of Content FeaturesHow the application worksSteps t
12 min read