Pre-requisites: To proceed with this blog, we are going to use one of my previous articles, only for the sake of the structure,
Getting started: We are required to connect to MySQL. Hence, I have a sample database already created in it with one table: users in it. The structure and the data of the table is given below:
Table Structure
Table Structure

Sample Data

Installing Package
Let’s now install MySQL Package in our Application. Open cmd in an administration mode and reach the folder directory of your project, enter command npm, install MySQL to install the MySQL package in your Application.


Connect DB
Now, let’s create a folder “config” in the project, add a file database.js file in our project and add the configuration to our db to connect it.
Now, let’s create a folder “config” in the project, add a file database.js file in our project and add the configuration to our db to connect it.
- var mysql = require('mysql');
- // Read more about mysql connection here : https://www.npmjs.com/package/mysql
- var connection = mysql.createConnection({
- host:'localhost',
- user:'root',
- password:'123456',
- database:'test'
- });
- exports.getConnected = function(){
- return connection;
- };
Including database.js
Include this database.js file in app.js. This is nothing more than including this file in the project. Please note that app.js is the first file to be executed in the project, including any file into it will include it in the whole Application.
- var dbConnect = require('./config/database');
- var con = dbConnect.getConnected();
Query We will now go ahead and create a DB query to call the data from the database.
- con.query('SELECT * FROM USERS',function(err,rows){
- if(err)
- console.log("Error has occured: "+ err);
- else
- console.log("Data: "+ JSON.stringify(rows));
- })

I hope this article provides good information regarding connecting Nodejs to MySQL db.

Akash NaginaPosted Sep 20, 2016, 10:37 AM
Nice article
pooja guptaPosted Sep 8, 2016, 6:46 AM
Very nice explanation. i was looking for this. thanks
kalu singh raoPosted Jul 8, 2016, 1:31 AM
Nice...