How to connect to a MySQL database in Node.js


Oct 12, 2021
featured image

About

To connect to a MySQL database in Node.js is pretty straightforward with the module mysql2. This example is just a starting point to show how to connect it so do not take it as a production-ready code

How to install it

Let's install the module in our project as usual

      
npm install mysql2
      
    

How to implement it

Create a file called database.js wit this content
      

const mysql = require("mysql2");
const pool = mysql.createPool({
  database: process.env.MYSQL_DATABASE,
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USERNAME,
  password: process.env.MYSQL_PASSWORD,
  port: Number(process.env.MYSQL_PORT),
  connectionLimit: Number(process.env.MYSQL_MAX_POOL_SIZE),
});

const query = (query, values = []) => {
  return new Promise((resolve, reject) => {
    pool.query(query, values, (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
};

module.exports.query = query;

      
    

How to use it

      

const db = require("./database");
const result = await db.query("SELECT NOW()");
console.log(result);

      
    

nodejs mysql mysql2 dev