How to Update Data of MySQL Database Using Node JS

Here you will learn how to Update Data of MySQL Database Using Node JS. To Update Data of MySQL Database, we will use the mysql2 module.

But, before going further, I suggest you first check out this –


Database Configuration

Database Nametest
Table Nameusers

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'
});

Update Data of MySQL Database


let _new_name = "Adam Smith";

db_connection.promise()
.execute("UPDATE `users` SET `name`=? WHERE `id`=?",[_new_name, 1])
.then(([result]) => {
    //console.log(result);
    if(result.affectedRows === 1){
        console.log("User Successfully Updated.");
    }
}).catch(err => {
    console.log(err);
});

Full Code of Update Data


const mysql = require('mysql2');
const db_connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'test',
    password:'your_db_password'
});

let _new_name = "Adam Smith";

db_connection.promise()
.execute("UPDATE `users` SET `name`=? WHERE `id`=?",[_new_name, 1])
.then(([result]) => {
    //console.log(result);
    if(result.affectedRows === 1){
        console.log("User Successfully Updated.");
    }
}).catch(err => {
    console.log(err);
});

Leave a Reply

Your email address will not be published. Required fields are marked *