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";Second, open a database connection to an SQLite database:
const db = new sqlite3.Database(filename);Third, execute a DELETE statement statement using the run() method of the Database object:
db.run(sql, params, callback);Finally, close the database connection:
db.close()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();Step 2. Open the terminal and execute the following command to run the Node.js app:
node delete.jsStep 3. Verify the deletion:
First, open a new terminal and use the sqlite3 tool to connect to the my.db database:
sqlite3 my.dbSecond, query data from the products table:
SELECT * FROM products;Output:
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 theDatabaseobject to execute anDELETEstatement to delete data from a table.
Thank you for your feedback!