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
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.
- var mysql = require('mysql');
-
-
- var connection = mysql.createConnection({
-
- host:'localhost',
- user:'root',
- password:'123456',
- database:'test'
- });
-
- exports.getConnected = function(){
- return connection;
-
- };
This code will connect to our local DB.The exports keyword here makes the function getConnected to be called in the other file.
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));
- })
The resultant output is displayed in the debug console of the Application,
I hope this article provides good information regarding connecting Nodejs to MySQL db.