Node.js MySQL Update Statement
Node.js is an open-source platform for executing JavaScript code on the server-side. It can be downloaded from here. MySQL is an open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the most popular language for adding, accessing, and managing content in a database. Here we will use the MySQL as a database for our node application. It can be downloaded from here.
Update statement: Update command is a DML command which is used for manipulating the records of a table.
Syntax:
UPDATE [table_name] SET column_A = value_A, column_B = value_B, ... WHERE condition
Modules:
- mysql: mysql module is used for interaction between the MySQL server and the node.js application.
Installing module:
npm install mysql
SQL publishers Table preview:
Example 1: Update all salary to 0.
// Importing module
const mysql = require("mysql");
// Creating connection
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err);
return;
}
console.log("We are connected to gfg_db database");
// Creating Query
let query = "UPDATE publishers SET salary=0";
// Executing Query
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
Run index.js file using below command:
node index.js
Console Output: Using the Where clause is very important in UPDATE. Otherwise, the whole table may become useless.
Example 2: Increase the salary of publishers by 1000 who are earning more than 7000.
// Importing module
const mysql = require("mysql");
// Creating connection
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err);
return;
}
console.log("We are connected to gfg_db database");
// Generating Query
let query =
"UPDATE publishers SET salary=salary+1000 WHERE salary > 7000";
// Executing Query
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
Run index.js file using below command:
node index.js
Console Output: Notice previous and current salary of users with id 6, 8