NodeJs – Connect With Mysql

We can use the NodeJs in Mysql application . lets see what are the procedures to use it inside the NodeJs environment.

Install MySql Database

First we have Mysql installed on our computer .if you don’t have
install MySql Database from https://www.mysql.com/downloads

Install MySql Driver

Once you have install the MySql database . we can start using Mysql database with NodeJs Application by installing the NPM module

To download and install the MySql Module enter the following in Command Prompt .

D:\node project >npm install mysql

Now we have downloaded and installed the MySql Module in your project.

You can make use this module to gain access to database operations.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost", //The DB Hostname in your Mysql Server
  user: "yourusername", //The DB Username in your Mysql Server
  password: "yourpassword" //The Db Password in your Mysql Server
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connection Established Successfully!");
});

Save the above code in a file name called “dbConnection.js” in your local folder and Run the file .

D:\node project >node dbConnection.js
Connection Established Successfully!

How To Query a Database

Using Sql statements to select,insert,delete operation in NodeJs application called querying a database.The above connection object has a method to querying a database .The method takes a query statement as a parameter and returns the result .

Lets see how to querying the database using above method .

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost", //The DB Hostname in your Mysql Server
  user: "StudentDb", //The DB Username in your Mysql Server
  password: "12345" //The DB Password in your Mysql Server
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connection Established Successfully!");
  con.query("SELECT * FROM Student", function (err, result) {
    if (err) throw err;
    console.log("Result Data:" + result);
  });
});

We will see further details on Querying a database using
read, write, delete, and update operations on the chapter “Creating a simple application with NodeJs” .

Next Chapter >> Connect with MongoDB

Leave a Reply

Your email address will not be published. Required fields are marked *