Here you will learn how to Delete Data from MySQL Database Using Node JS. To Delete Data from MySQL Database, we will use the mysql2
module.
But, before going further, I suggest you first check out this –
- Create MySQL Database Connection with Node JS
- How to Query a MySQL Database using Node JS
- Insert Data Into MySQL Database Using Node JS
- Fetch (Select) Data From MySQL Database Using Node JS
- Update Data of MySQL Database Using Node JS
Database Configuration
Database Name – test
Table Name – users
So first, Strat your MySQL Server and create a Database called test, and then inside the test database create a table called users.
Use the following SQL Code to create users
table and the structure of the users
table.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`age` int(11) NOT NULL,
`email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Database Connection
const mysql = require('mysql2');
const db_connection = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
password:'your_db_password'
});
Delete Data of MySQL Database
db_connection.promise()
.execute("DELETE FROM `users` WHERE `id`=?",[1])
.then(([result]) => {
if(result.affectedRows === 1){
console.log("User Successfully Deleted.");
}
}).catch(err => {
console.log(err);
});
Full Code of Delete Data
const mysql = require('mysql2');
const db_connection = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
password:'your_db_password'
});
db_connection.promise()
.execute("DELETE FROM `users` WHERE `id`=?",[1])
.then(([result]) => {
if(result.affectedRows === 1){
console.log("User Successfully Deleted.");
}
}).catch(err => {
console.log(err);
});