Open In App

How to Use Connection Pooling with MySQL in Node.js?

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 a database:
CREATE DATABASE geeksforgeeks;
  • Create a table:
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.

dbstruct
Database and table creation in mysql workbench

Project structure:

gfg1
Project structure

Step 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.

[ ] 
initial
Fetching data from users

Note: 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
Insert data in table

After inserting data, table will looks like this:

select
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.


Next Article
Article Tags :

Similar Reads