After insertion, we need to delete records as well. The records should can be deleted based upon an identifier from the database table. You can delete records from table using "DELETE FROM" statement. We can delete the records from MySql DB in two ways &m...
After insertion, we need to delete records as well. The records should can be deleted based upon an identifier from the database table. You can delete records from table using "DELETE FROM" statement.
We can delete the records from MySql DB in two ways −
Static Deletion - In this type of deletion, we give a prefixed filter value to delete
Dynamic Deletion – In this type of deletion, we ask for an input before deletion and then delete upon its basis.
Before proceeding, please check the following steps are already executed −
mkdir mysql-test
cd mysql-test
npm init -y
npm install mysql
The above steps are for installing the Node - mysql dependecy in the project folder.
Following are the examples on how to delete records from MySql using Nodejs.
For deleting records from the MySQL table, create an app.js file.
Now copy-paste the below snippet in the file
Run the code using the following command
>> node app.js
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) throw err; //Delete the records with address="Delhi" var sql = "DELETE FROM student WHERE address = 'Delhi'; " con.query(sql, function (err, result) { if (err) throw err; console.log("Record deleted = ", results.affectedRows); console.log(result); }); });
Record deleted = 1 OkPacket { fieldCount: 0, affectedRows: 1, // No of Records Deleted insertId: 0, serverStatus: 34, warningCount: 0, message: '', protocol41: true, changedRows: 0 }
The following example will take address field as the input and only delete the records which match the filter.
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) throw err; // Delete the desired record from table let sql = `DELETE FROM student WHERE address = ?`; // delete a row with address=Delhi con.query(sql, 'Dehi', (err, result, fields) => { if (err) throw err; console.log("Record deleted = ", results.affectedRows); console.log(result); }); });
OkPacket { fieldCount: 0, affectedRows: 3, // 3 Rows deleted for address=Delhi insertId: 0, serverStatus: 34, warningCount: 0, message: '', protocol41: true, changedRows: 0 }