How to Use Transactions in MySQL with NodeJS?
Last Updated :
30 Aug, 2024
Transactions in MySQL are used to execute a series of operations as a single unit of work, ensuring that all operations either succeed or fail together. This is crucial in maintaining data integrity, especially when dealing with complex operations that involve multiple database queries. In Node.js, transactions can be implemented using various approaches to ensure that either all changes are committed to the database or none at all, preventing partial updates.
Steps to Create the Application
Step 1: Initialize a Node.js Project
Create a new Node.js project and navigate to the project directory:
mkdir mysql-transaction-demo
cd mysql-transaction-demo
npm init -y
Step 2: Install Required Modules
Install the MySQL module:
npm install mysql2
Project Structure:
Project structureStep 3: Create a Database and Tables
Before running the Node.js code, create a MySQL database and the necessary tables:
CREATE DATABASE transaction_demo;
USE transaction_demo;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE TABLE logs (
id INT AUTO_INCREMENT PRIMARY KEY,
log TEXT NOT NULL
);
Note: Open your terminal in mysql server paste above code then press Ctrl+Enter as shown in above figure.
Updated Dependencies:
{
"name": "mysql-transaction-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mysql2": "^3.11.0"
}
}
Example: Here's an example of using the async/await for transactions.
JavaScript
// index.js
const mysql = require('mysql2/promise');
async function executeTransaction() {
const config = {
host: 'localhost',
user: 'root',
password: '',
database: 'transaction_demo'
};
const connection = await mysql.createConnection(config);
await connection.beginTransaction();
try {
const [result1] = await connection.query('INSERT INTO users SET ?', { name: 'John' });
const log = 'User ' + result1.insertId + ' added';
const [result2] = await connection.query('INSERT INTO logs SET ?', { log: log });
await connection.commit();
console.log('Transaction Completed Successfully.');
} catch (err) {
await connection.rollback();
console.error('Transaction Failed:', err);
} finally {
await connection.end();
}
}
executeTransaction();
Output:
Transaction completed successfully.The output can be visualized by checking the entries in the users and logs tables. If the transaction is successful, both tables will have new entries. If it fails, no entries will be made.