Node.js MySQL Update

🚀 Node.js MySQL – UPDATE Records

The UPDATE statement is used to modify existing records in a table.

We’ll use mysql2 for all examples.


1. Install mysql2

npm install mysql2

2. Connect to MySQL Database

const mysql = require("mysql2");

const connection = mysql.createConnection({
host: “localhost”,
user: “root”,
password: “”,
database: “mydb”
});


3. Update a Single Record

const sql = "UPDATE users SET name = ? WHERE id = ?";
const values = ["John Updated", 1];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log(“Affected Rows:”, result.affectedRows);
});

Output Example:

Affected Rows: 1

4. Update Multiple Records

const sql = "UPDATE users SET name = ? WHERE email LIKE ?";
const values = ["Anonymous", "%example.com%"];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log(“Affected Rows:”, result.affectedRows);
});


5. Update Without WHERE (Update All Rows)

⚠️ Be careful! This will update all rows in the table.

connection.query("UPDATE users SET name = 'Default Name'", (err, result) => {
if (err) throw err;
console.log("All rows updated. Affected Rows:", result.affectedRows);
});

6. Using Async/Await (Promise API)

const mysql = require("mysql2/promise");

async function updateUser(id, newName) {
const connection = await mysql.createConnection({
host: “localhost”,
user: “root”,
password: “”,
database: “mydb”
});

const sql = “UPDATE users SET name = ? WHERE id = ?”;
const [result] = await connection.execute(sql, [newName, id]);

console.log(“Affected Rows:”, result.affectedRows);
await connection.end();
}

updateUser(1, “Chris Updated”);


7. Update Multiple Columns

const sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
const values = ["Alice Updated", "alice_updated@example.com", 2];
connection.query(sql, values, (err, result) => {
if (err) throw err;
console.log(“Affected Rows:”, result.affectedRows);
});


8. Best Practices

Practice Reason
Always use WHERE Avoid updating all rows unintentionally
Use prepared statements (?) Prevent SQL injection
Wrap in try/catch when using async/await Catch errors safely
Validate input Prevent invalid data

You may also like...