Export Node.js SQL connection to multiple ROUTES routes

Oct 3, 2018 1 min read
Export Node.js SQL connection to multiple ROUTES routes

Motivation

We have an app and we want to divide/organize our folder. We also want to use the database connection on multiple locations without having to re-write the same code millions of times.

Steps

The steps are very simple, we only need to organize them:

  1. Create in a separate file your DB Connection.
  2. Require that file on your desired route.

Get the code

File: db.js

var mysql = require('mysql');

// Create connection
function connection() {
    const db = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '123456',
      database: 'mySchema'
    });

    db.connect(function (err) {
      if (!err) {
        console.log('Database is connected!');
      } else {
        console.log('Error connecting database!');
      }
    });
  return db;
}

module.exports = connection();

File: routeX.js

dbConnection = require('../config/db.js');

 //TEST YOUR DB CONNECTION
dbConnection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

There is a better way of creating connection than the above, it's called pooling connections, in case someone is interested.

Hope that helps,

Arturo

Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.