How to Create and Use Functions in MySQL with NodeJS?
Last Updated :
03 Sep, 2024
We will learn how to create and use functions in MySQL with Node.js. MySQL functions allow encapsulating complex calculations and business logic within the database, which can then be called from Node.js applications. This method is particularly useful for reusing SQL code and maintaining a clean application structure.
Steps to Create the Application
Step 1: Initialize the Node.js Application
First, create a new directory for your application and initialize a new Node.js project.
mkdir mysql-functions-app
cd mysql-functions-app
npm init -y
Step 2: Install Required Modules
Install the mysql package to interact with MySQL from Node.js.
npm install mysql
Project Structure:
Project structureUpdated Dependencies:
{
"name": "mysql-functions-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mysql": "^2.18.1"
}
}
Step 3: Create the MySQL Database and Function
- Open your MySQL client (e.g., MySQL Workbench, phpMyAdmin, or the command-line interface).
- Connect to your MySQL server.
- Select the database where you want to create the function.
- Create a MySQL Database (if not already done):
CREATE DATABASE my_database;
USE my_database;
- Run above command in your databse terminal i'm using phpmyadmin console.
This will create a databse named my_database- Create the Function in MySQL: Run the following SQL code in your MySQL client:
CREATE FUNCTION add_numbers(a INT, b INT)
RETURNS INT
BEGIN
RETURN a + b;
END;
OR
DELIMITER //
CREATE FUNCTION add_numbers(a INT, b INT)
RETURNS INT
BEGIN
RETURN a + b;
END //
DELIMITER ;
database
Step 4: Set Up the Node.js Application
Create the necessary files in your Node.js project.
- Create db.js for MySQL Connection:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'my_database'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL');
});
module.exports = connection;
- Create index.js for Running the Function:
const connection = require('./db');
const query = 'SELECT add_numbers(5, 10) AS result;';
connection.query(query, (error, results) => {
if (error) throw error;
console.log('Result:', results[0].result);
});
connection.end();
Example: This example shows the use of function in MySQL with NodeJS.
JavaScript
//db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'my_database'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL');
});
module.exports = connection;
JavaScript
//index.js
const connection = require('./db');
const query = 'SELECT add_numbers(5, 10) AS result;';
connection.query(query, (error, results) => {
if (error) throw error;
console.log('Result:', results[0].result);
});
connection.end();
Output:
To see the output:
- Run the Node.js application by executing the following command in your terminal:
node index.js
OutputConclusion
By following this guide, you’ve successfully created a function in MySQL and integrated it with a Node.js application. This method allows you to encapsulate business logic directly within the database, making your application more modular and maintainable. Leveraging MySQL functions in your Node.js applications can significantly streamline your codebase, enabling easier management and better performance for database-related operations.
Similar Reads
How to Create and Use Stored Procedures in MySQL with Node.js?
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 M
3 min read
How to Use Connection Pooling with MySQL in Node.js?
MySQL is one of the most preferred relational databases, While Node.js is another name for JavaScript runtime environment. While assessing a large number of connections in the database in a Node. In this regard, effectiveness in managing them is also a significant determinant when developing and mai
3 min read
How to Make a search function using Node Express and MYSQL
In this article, we will learn how to create a search function using Node with Express framework to search terms inside MYSQL tables. Prerequisites:MySQLNode JSExpress JSWe will discuss the following methods to search: Table of Content Searching term with partial matchSearching term with exact match
5 min read
How to use .env file in NodeJS MySQL?
Environment variables are list of properties defined by key and value used for storing configurations data for instance the database credentials, api keys and so on. In the past, these values were directly coded into your applicationsâ code and were not flexible to change, but today we can store the
4 min read
Node.js MySQL FIND_IN_SET() Function
FIND_IN_SET() function is a built-in function in MySQL that is used to get the position of the first occurrence of value string in a list of strings separated by comma(','). Syntax: FIND_IN_SET(value, list_of_string)Parameters: It takes two parameters as follows: value: It is the value to be searche
2 min read
How To Build Node.js Authentication System With MySQL?
Node.js is an open-source server-side JavaScript runtime environment established to develop server-side applications. The first task can be an implementation of an authentication system, this is one of the most frequently used processes in web development. In this article, we are going to learn how
4 min read
How to Use Transactions in MySQL with NodeJS?
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,
2 min read
How to Dynamically Call Router Function in Node.js ?
In Node.js Dynamically calling a router function means that the function is selected at runtime based on the request parameters, instead of being explicitly defined in the code. This can be useful when you want to handle a large number of similar requests without having to define a separate function
4 min read
What are the Risks of using mysql_* Functions in PHP?
MySQL functions in PHP, often referred to as mysql_* functions, have been a popular choice for developers to interact with MySQL databases. Did you say "NOT ANYMORE!"? So now it's essential to weigh the pros and cons of mysql_* functions in PHP to determine whether they are a good or bad choice for
4 min read
How to Use math.js in NodeJS And Browser?
Math.js can be used to perform complex mathematical computations in both NodeJS and browser environments. It is a powerful library that supports a wide range of mathematical functions, including algebra, calculus, and statistical operations. By integrating math.js into your projects, you can handle
3 min read