Summary: in this tutorial, you will learn how to delete data in the SQLite database from a Node.js application.
This tutorial begins where the “Update data in a Table from Node.js” tutorial left off.
Deleting data from a table in Node.js
To delete data in an SQLite table from a Node.js app, you follow these steps:
First, import sqlite3
from the sqlite3
module:
import sqlite3 from "sqlite3";
Code language: JavaScript (javascript)
Second, open a database connection to an SQLite database:
const db = new sqlite3.Database(filename);
Code language: JavaScript (javascript)
Third, execute a DELETE
statement statement using the run()
method of the Database
object:
db.run(sql, params, callback);
Code language: JavaScript (javascript)
Finally, close the database connection:
db.close()
Code language: JavaScript (javascript)
Deleting Data from a table
Step 1. Add the delete.js
file to delete the data in the products
table:
import sqlite3 from "sqlite3";
import { execute } from "./sql.js";
const main = async () => {
const db = new sqlite3.Database("my.db");
const sql = `DELETE FROM products WHERE id = ?`;
try {
await execute(db, sql, [1]);
} catch (err) {
console.log(err);
} finally {
db.close();
}
};
main();
Code language: SQL (Structured Query Language) (sql)
Step 2. Open the terminal and execute the following command to run the Node.js app:
node delete.js
Code language: JavaScript (javascript)
Step 3. Verify the deletion:
First, open a new terminal and use the sqlite3
tool to connect to the my.db
database:
sqlite3 my.db
Code language: JavaScript (javascript)
Second, query data from the products
table:
SELECT * FROM products;
Code language: SQL (Structured Query Language) (sql)
Output:
Code language: JavaScript (javascript)
The output indicates that the program has deleted a row from the products
table so the result set is empty.
Summary
- Use the
run()
method of theDatabase
object to execute anDELETE
statement to delete data from a table.