How to Create and Use Stored Procedures in MySQL with Node.js?
Last Updated :
21 Aug, 2024
Stored procedures in MySQL are very useful in the following ways Regarding the encapsulation of business logic within a database. They can be run multiple times and do not cause a large load on the client-server connection. In this tutorial, we will learn how to create and use stored procedures in MySQL with the help of a Node.js application.
Prerequisites
Steps on the Formation and Utilization of MySQL Procedures from Node.js
Step 1: Setting up the node.js Project
- Create a new Node.js project using the following command:
mkdir geeksforgeeks
cd geeksforgeeks
npm init -y
- Install mysql2 dependency using npm:
npm install mysql2
Project Structure:
Project structure in VS codePackage.json:
{
"name": "geeksforgeeks",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"license": "ISC",
"dependencies": {
"mysql2": "^3.11.0"
}
}
Step 2: Create Database, Tables and Stored Procedures in MySQL
- Open the MySQL client you prefer (for example, MySQL Workbench, phpMyAdmin or simple command line).
- Create a database:
CREATE DATABASE geeksforgeeks;
USE geeksforgeeks;
- Create a table to use in our stored procedure:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL
);
- Create a stored procedure to insert data into the table:
DELIMITER //
CREATE PROCEDURE InsertUser(IN userName VARCHAR(255), IN userEmail VARCHAR(255))
BEGIN
INSERT INTO users (name, email) VALUES (userName, userEmail);
END //
DELIMITER ;
- Create a stored procedure to fetch user data:
DELIMITER //
CREATE PROCEDURE GetUser(IN userId INT)
BEGIN
SELECT * FROM users WHERE id = userId;
END //
DELIMITER ;
Database Queries in mysql workbenchStep 3: Insert data and use Stored Procedure in the Node.js
This step engages the use of MySQL to connect to the database and call the stored procedures from the app.js:
JavaScript
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'yourpassword',
database: 'geeksforgeeks'
});
// Connect to the database
connection.connect((err) => {
if (err) throw err;
console.log('Connected to the MySQL server.');
});
// Function to insert a new user
function insertUser(name, email, callback) {
connection.query('CALL InsertUser(?, ?)',
[name, email], (err, results) => {
if (err) return callback(err);
callback(null, results);
});
}
// Function to call the stored procedure to get a user
function getUser(userId, callback) {
connection.query('CALL GetUser(?)',
[userId], (err, results) => {
if (err) return callback(err);
callback(null, results[0]);
});
}
// Insert a new user
insertUser('Geek', '[email protected]', (err, result) => {
if (err) throw err;
console.log('User Inserted Successfully.');
// Retrieve the user data
getUser(1, (err, result) => {
if (err) throw err;
console.log('User Details:', result);
connection.end();
});
});
Output:
OutputConclusion
Storing and retrieving data through stored procedures in Mysql with Node.js focuses on establishing your project, determination of the stored procedures in relation to data manipulation along with invoking these procedures from your Node.js application. Here, it assists in handling intricate procedures and keeps the relationships between your databases managed.