Node js MySQL Update Data

UPDATE command is used to update data in the table. In this code, the 'SET' clause is used with the UPDATE table to set values for updating columns and the modifying columns are separated by comma. The 'WHERE' clause is used to apply condition to update rows. You can update one or many rows fields together.

Syntax

UPDATE Tablename SET column1 = ? [WHERE Clause];

Example

In this given example, we have updated the name of the id #3 of the 'department' table.

var mysql = require("mysql");
var con = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: 'myadmin',
   database: 'demo'
});
con.connect(function(error){
    if(error) {
        console.log('Error establishing connection to db');
        return;
    }
    console.log('Connection Established'); 
    var updatedata = "UPDATE department SET name = ? WHERE id = ?";
    con.query(updatedata, ["Sales", 3], function (error) {  
    if(error) { 
        throw(error);
    }  
    console.log("Data Updated");  
    });  
});

Open cmd and run the above file as -

nodejs mysql update data

Read more articles


General Knowledge



Learn Popular Language