Node and MySQL is a go-to combination for a quick prototype build and in various cases for production build as well. In this tutorial, we will learn how to connect Node with MySQL and how to pool the connections for better performance and optimization of resources.

You need Node and MySQL installed in your system before proceeding towards the tutorial. To keep the tutorial on the point, I am not going to show you the steps to install this software, a simple Google search will do just fine.

Node MySQL Connection

To begin with, create a new folder and initialize a new Node project using the command shown below.

npm init --y

Now, install the required node modules.

npm install --save mysql

Now, copy and paste the code shown below in a file and name it app.js.

const mysql = require('mysql');

const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'username',
  password : 'password',
  database : 'databasename'
});

connection.connect((err) => {
    if(err) throw err;
    console.log('Connected to MySQL Server!');
});

Now, run the code and see the output on the terminal.

node app.js

You should see the following message in the terminal.

Connected to MySQL Server!

Our code successfully made a connection to the MySQL server. We can now perform any database operations we like. This code is not enough though, we need to implement the connection pool to achieve our goal.

What is Connection Pooling?

In a nutshell, the Connection pool is similar to a cache where we store frequently accessed data. Here the data is a database connection. The goal is to achieve the reusability of the database connections instead of creating a new connection every time there is a demand for the data.

Node MySQL Connection Pool Example

Here is the code with MySQL connection pool implementation.

const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'yourmysqlusername',
    password : 'yourmysqlpasword',
    database : 'yourdbname',
    debug    :  false
});

pool.query("SELECT * FROM TABLE_NAME",(err, data) => {
    if(err) {
        console.error(err);
        return;
    }
    // rows fetch
    console.log(data);
});

Now run the code and observe the output. It should return all the entries of the table. Kindly change the details in the code with your own MySQL configuration.

Conclusion

This is an on-point and simple tutorial to teach you how to connect Node and MySQL. You can read our in-depth tutorial on Node and take our FREE node course to learn more about Node.