Updating MySQL Records with Node.js: A Practical Guide to Modifying Database Data

Learn how to update records in a MySQL database using Node.js. This tutorial provides a step-by-step guide, demonstrating the `UPDATE` command with a `WHERE` clause, and emphasizes the importance of error handling and parameterized queries for secure and efficient database operations.



Updating Records in MySQL Using Node.js

Introduction

This tutorial demonstrates updating records in a MySQL database using Node.js. We'll use the `UPDATE` SQL command with a `WHERE` clause to target specific rows for modification.

Prerequisites

  • Node.js and npm installed.
  • MySQL server running.
  • MySQL Connector/Node.js installed (`npm install mysql`).
  • A database named `tutorialsarena`.
  • A table named `employees` with columns `id`, `name`, `age`, and `city` (populated with sample data).

Updating a Record

This example updates the city of the employee with id '1' from 'Allahabad' to 'Delhi':

Updating a Record

const mysql = require('mysql');
const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "your_password", // Replace with your MySQL root password
  database: "tutorialsarena"
});

con.connect(function(err) {
  if (err) throw err;
  var sql = "UPDATE employees SET city = 'Delhi' WHERE id = '1'";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result.affectedRows + " record(s) updated");
  });
});

Save this code as `update.js` and run it using `node update.js` from your terminal.

Verifying the Update

(Instructions on how to verify the update, perhaps showing a `SELECT` query to retrieve the updated record from the `employees` table, would be included here. The example should show the `SELECT` query and its expected output, illustrating that the city has changed from "Allahabad" to "Delhi".)

Conclusion

This tutorial showed how to update records in MySQL using Node.js and the `UPDATE` command. Remember to always include error handling in your code and use parameterized queries (not shown in this example) to prevent SQL injection vulnerabilities.