Myqsl connection with node js express tutorial for your mern stack

Myqsl connection with node js & express js tutorial

This tutorial focuses on helping you to use MySQL on your node js apps. create a file called db.js and paste these lines of code in it

const mysql = require("mysql");

var db;
connectDatabase = () => {
  if (!db) {
    db = mysql.createConnection({
      host: "localhost",
      user: "",
      password: "",
      database: "",
    });
    db.connect(function (err) {
      if (!err) {
        console.log("Database is connected!");
      } else {
        console.log("Error connecting database!");
      }
    });
  }
  return db;
};
module.exports = connectDatabase();

Then inside your router handler you can use it to make a database query calls. But the best practice for the settings is that you make use of .env variable to store all your database details and then fill them this way.


const mysql = require("mysql");
var db;
connectDatabase = () => {
  if (!db) {
    db = mysql.createConnection({
      host: process.env.DBHOST,
      database: process.env.DBNAME,
      user: process.env.DBUSER,
      password: process.env.DBPASSWORD,
    });
    db.connect(function (err) {
      if (!err) {
        console.log("Database is connected!");
      } else {
        console.log("Error connecting database!");
      }
    });
  }
  return db;
};
module.exports = connectDatabase();


That should give you a simple neat solution. Please make sure to share with your friends.