How to Create MySQL Database Connection (pool) with Node JS

Here you will learn how to Create MySQL Database Connection (pool) with Node JS.

To Create the Database Connection with MySQL DB Using Node JS, we will use the mysql2 module.

So first, initialize NPM in your app folder, and then install the mysql2 module. Run the following command to install it –

npm install --save mysql2

After installing the mysql2 module, Now import it into the index.js or your entry file.

const mysql = require('mysql2');

But, before creating a Database Connection, first, you need to create a Database into your MySQL server.

Creating a DB connection using createConnection

const mysql = require('mysql2');

const db_connection = mysql.createConnection({
    host:'localhost', // HOST NAME
    user:'root', // USER NAME
    database:'your_db_name', // DATABASE NAME
    password:'your_db_password' // DATABASE PASSWORD

db_connection.on('error', (err) => {
    if(err) throw err;

Now run the following command in your terminal to run your app. And make sure that your MySQL Server is running.

node index

If there is no error in your console, that means you are successfully connected to your Database.

Making DB Connection Using connection pools

You can also create Database Connection using connection pools. But,

Why we use connection pools?

Connection pools help reduce the time spent connecting to the MySQL server by reusing a previous connection, leaving them open instead of closing when you are done with them.

This improves the latency of queries as you avoid the overhead that comes with establishing a new connection.

const mysql = require('mysql2');
const db_connection = mysql.createPool({
    host: 'localhost', // HOST NAME
    user: 'root', // USER NAME
    database: 'your_db_name', // DATABASE NAME
    password: 'your_db_password' // DATABASE PASSWORD

This will work the same as mysql.createConnection()

If you want to catch the pool connection error, then you can use the try-catch block.

const mysql = require('mysql2');
    const db_connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        database: 'your_db_name',

How to close Database Connection?

If you want close Database Connection Manually, then use the end() method or function.


Leave a Reply

Your email address will not be published. Required fields are marked *