- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js MySQL Update
In any dynamic application, data isn't static. Whether a user is changing their profile picture, a shop manager is updating stock levels, or a system is marking an order as "shipped," you need the UPDATE statement. In Node.js, combined with the MySQL driver, this allows you to modify existing database records programmatically based on user input or system events.
SELECT query with the same WHERE clause to preview exactly which rows will be affected.
Key Features of Node.js MySQL Update
- Precision Targeting: Use the
WHEREclause to isolate specific records, ensuring you don't overwrite the entire database by mistake. - Efficiency: Update multiple fields (columns) in a single round-trip to the database server.
- Data Integrity: Wrap updates in Transactions to ensure that if one part of a multi-step process fails, the database remains in its original state.
- Dynamic Filtering: Use logical operators like
AND,OR, andBETWEENto target complex subsets of data.
? placeholders) instead of inserting variables directly into your query strings. This is the primary defense against SQL Injection attacks.
Step 1 Prerequisites
To follow along, you need a Node.js environment set up and the mysql2 driver installed. We recommend mysql2 over the original mysql package because it is faster and supports modern features like Promises and Prepared Statements.
npm install mysql2
Step 2 Basic Query to Update Data
The UPDATE statement follows a specific syntax. You name the table, use the SET keyword to define new values, and—most importantly—provide a WHERE condition.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example Code for Updating Data
In this example, we connect to the database and update a single user's age. Notice the use of ? placeholders to keep the query secure.
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'testdb'
});
connection.connect((err) => {
if (err) {
console.error('Connection failed:', err.message);
return;
}
// Define the new value and the filter criteria
const newAge = 30;
const userName = 'John Doe';
// We use '?' as placeholders for security
const updateQuery = 'UPDATE users SET age = ? WHERE name = ?';
connection.query(updateQuery, [newAge, userName], (err, results) => {
if (err) {
console.error('Update failed:', err.message);
return;
}
// results.affectedRows tells us how many records matched and were updated
console.log(`Update successful! Rows affected: ${results.affectedRows}`);
});
connection.end();
});
Output:
Update successful! Rows affected: 1
WHERE clause doesn't match any rows, affectedRows will be 0. This is not technically an "error" in MySQL, so your code should handle this case if you expected an update to happen.
Step 3 Update Multiple Columns
In real-world scenarios, like a "Settings" page, users often update multiple fields at once (e.g., changing both their email and their display name).
Example Code for Updating Multiple Columns
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'testdb'
});
connection.connect((err) => {
if (err) return console.error(err.message);
const updatedData = [28, '[email protected]', 'Jane Doe'];
const updateQuery = 'UPDATE users SET age = ?, email = ? WHERE name = ?';
connection.query(updateQuery, updatedData, (err, results) => {
if (err) {
console.error('Error during multi-column update:', err.message);
return;
}
console.log('Record updated successfully.');
});
connection.end();
});
SET clause. It should be SET col1 = val1, col2 = val2 (comma separated), not SET col1 = val1 AND col2 = val2.
Step 4 Update with Conditions
The WHERE clause isn't limited to simple equality (=). You can use comparison operators to perform bulk updates, such as activating all users who have verified their accounts or flagging accounts over a certain age.
Example Code for Conditional Update
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'testdb'
});
connection.connect((err) => {
if (err) return console.error(err.message);
// Example: Mass update status for users older than 30
const status = 'active';
const minAge = 30;
const updateQuery = 'UPDATE users SET status = ? WHERE age > ?';
connection.query(updateQuery, [status, minAge], (err, results) => {
if (err) return console.error(err.message);
console.log(`Bulk update complete. ${results.affectedRows} users are now active.`);
});
connection.end();
});
WHERE clause entirely, MySQL will update every single row in the table. This is one of the most common ways to accidentally corrupt a production database.
Step 5 Using Transactions for Update
Transactions are essential for "all-or-nothing" operations. For example, if you are transferring money between two accounts, you need to update both rows. If the second update fails, you must cancel (rollback) the first one so money doesn't disappear into thin air.
Example Code with Transaction
const mysql = require('mysql2');
const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'testdb' });
connection.beginTransaction((err) => {
if (err) throw err;
const updateQuery = 'UPDATE users SET age = ? WHERE name = ?';
connection.query(updateQuery, [35, 'Sam Smith'], (err, results) => {
if (err) {
return connection.rollback(() => {
console.error('Transaction failed, changes rolled back.');
});
}
connection.commit((err) => {
if (err) {
return connection.rollback(() => {
console.error('Commit failed, changes rolled back.');
});
}
console.log('Transaction successfully committed.');
});
});
});
mysql2/promise. It makes handling nested callbacks and transactions much cleaner and easier to read.
Step 6 Using LIMIT with Update
The LIMIT clause restricts the number of rows that an UPDATE statement can modify. This is useful for processing data in batches or as a safety net to ensure a query doesn't spiral out of control.
Example Code for Update with Limit
const mysql = require('mysql2');
const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'testdb' });
connection.connect((err) => {
if (err) return console.error(err.message);
// Only update the first 2 inactive users found
const updateQuery = 'UPDATE users SET status = "active" WHERE status = "inactive" LIMIT 2';
connection.query(updateQuery, (err, results) => {
if (err) return console.error(err.message);
console.log(`Batch update finished. Affected rows: ${results.affectedRows}`);
});
connection.end();
});
Summary
The MySQL UPDATE statement is a powerful tool for maintaining your application's state. By using Node.js and the mysql2 library, you can perform precise single-row updates, broad bulk changes, and secure transactions. Always prioritize prepared statements to prevent SQL injection, and double-check your WHERE clauses to ensure you're only modifying the data you intend to change.