Nodejs Mysql update query

to create the MySQL update 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 change user name from John to Sunny and age from 35 to 31 which has userid 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 update.js file and include the connection.js file and write the update 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('update users SET name=?,age=? where id=?',['Sunny',31,1], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the update.js file.


node update.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ‘(Rows matched: 1 Changed: 1 Warnings: 0’,
protocol41: true,
changedRows: 1 }

Now, get the records from the users table.


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