How to connect to a MySQL database in Node.js

Flying Through a Crack in the Ice
Reading Time: < 1 minutes

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);

      
    
, ,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: