How to Use Connection Pooling with MySQL in Node.js?
Last Updated :
14 Aug, 2024
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 maintaining a js application. That is when connection pooling comes into the picture. Connection caching enable reusing connections to the databases instead of having to open a fresh connection with the database each time that a query is executed.
Prerequisites
Steps to Apply Connection Pooling in Node.js
Step 1: Create a NodeJS application
Ensure you have Node.js which is the JavaScript runtime and npm which is the node package manager installed on your system. Then, create a Node.js project and install the mysql2 package:
mkdir geeksforgeeks
cd geeksforgeeks
npm init -y
npm install mysql2
Updated dependencies:
"dependencies": {
"mysql2": "^3.11.0",
}
Step 2: Create MySQL Database and a Table
It is necessary to create a MySQL database and table before starting the connection pool so here we have to go through that step.
CREATE DATABASE geeksforgeeks;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The following is an SQL script that helped in creating a database on the name of geeks for geeks and a user table with id, name, email, and created_at fields.
Database and table creation in mysql workbenchProject structure:
Project structureStep 3: Create a connection pool in db.js file
In your db.js file, connection pool can be made by using mysql2 package.
JavaScript
// db.js
const mysql = require('mysql2');
// Create a connection pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'geeksforgeeks',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = pool;
Step 4: Querying the Database Using the Pool in index.js file
Actually, with the help of the connection pool and its configurations, you can begin querying the database now. For each query to be run, a connection shall be used from the connection pool in index.js file and once the query is executed, the connection is closed and again put back in the pool.
Example 1: Basic Query with Connection Pool
JavaScript
// index.js
const pool = require('./db');
pool.query('SELECT * FROM users', function(err, results, fields) {
if (err) throw err;
console.log(results);
});
Step 5: Run the application:
node index.js
Output: This will retrieve all the rows from the users table.
[ ]
Fetching data from usersNote: Initially, the table was empty that is why we have received empty array.
Example 2: The following is an example of how to insert data with connection pool, a new user is inserted into the users table. The results.insertId contains the ID of the newly inserted row.
JavaScript
const pool = require('./db');
const user = { name: 'John Doe', email: '[email protected]' };
pool.query('INSERT INTO users SET ?', user, function(err, results) {
if (err) throw err;
console.log('Inserted Row ID:', results.insertId);
});
Output: After the row is inserted, the ID of the inserted row is printed in the log.
Inserted Row ID: 1
Insert data in tableAfter inserting data, table will looks like this:
Fetching data from table after insertion Conclusion
Connection pooling with MySQL in Node.js is a good thing to use to make your application run effectively in the way that re-uses the connections to the database. Compared to the mysql package, the mysql2 package is easy to use to implement connection pooling as well as to control and run queries.
Similar Reads
What is Connection Pooling with MongoDB in Node.js ?
In this article, we are going to see in-depth connection pools MongoDB in Nodejs. A connection pool serves as a collection of established TCP connections that your application's MongoDB driver maintains with a MongoDB server. This pool's purpose is to minimize the need for frequent network handshake
2 min read
How to Create and Use Functions in MySQL with NodeJS?
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 ap
3 min read
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
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, cover
2 min read
How to Use Prepared Statements in MySQL with Node.js
MySQL prepared a database by pre-compiling the SQL query with a set of placeholders for parameters. You could use the MySQL2 or MySQL library to be connected to your MySQL database and execute queries by passing the SQL statement with an array of values for the placeholders. It prevents SQL injectio
10 min read
How to make a connection with MySQL server using PHP ?
MySQL is a widely used database management system that may be used to power a wide range of projects. One of its main selling features is its capacity to manage large amounts of data without breaking a sweat. There are two approaches that can be used to connect MySQL and PHP code, which are mentione
3 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 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 Use ORM Connection Pooling Effectively
In software development, efficient database connection management is important for optimal performance and scalability. Object-Relational Mapping (ORM) has revolutionized database interactions, simplifying SQL queries. However, even with advanced ORM frameworks, poor connection management can impact
8 min read
How to connect mongodb Server with Node.js ?
mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module. Syntax: mongodb.connect(path,callbackfunction)Parameters: This method accept two parameters as mention
2 min read