Nodejs Mysql delete query

to create the MySQL delete query in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now you want to delete user which has user id is 1

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the delete.js file and include the connection.js file and write the delete query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('delete from users where id=?',[1], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the delete.js file.


node delete.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

Now, get the users records from the table.


Select * from users
Output:-
ID
Name
Age
2
Rom
31
3
Mathew
32
4
Sachin
38