Deleting MySQL Records using Node.js: A Practical Guide
Learn how to delete records from a MySQL database using Node.js. This tutorial provides a clear, step-by-step guide with code examples demonstrating how to execute `DELETE` statements, handle potential errors, and verify the results, essential for database management tasks.
Node.js MySQL Delete Records
This section shows how to delete records from a MySQL table using Node.js. The `DELETE FROM` command is used for this purpose.
Deleting Records Based on a Condition
Let's delete employees from the 'employees' table where the city is 'Delhi'. Create a file named `delete.js` with this code:
Deleting Records
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345", // Replace with your password
database: "tutorialsarena" // Replace with your database name
});
con.connect(function(err) {
if (err) throw err;
var sql = "DELETE FROM employees WHERE city = 'Delhi'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
Remember to replace `"12345"` with your actual MySQL password and `"tutorialsarena"` with your database name. Run the script using `node delete.js`. The output shows the number of rows affected (deleted). You can verify the deletion by using a `SELECT` statement to check the remaining records in the `employees` table.
next →
← prev