Node.Js : Connecting with SQL database & retrieve data

First node-mysql package should be installed using npm in your project. (make sure you have installed node.js)

It can be done with code npm install mysql 

Lets get in to code,

  • Add the "mysql" module to application
    var mysql = require("mysql");

  • Creating a connection object for sql connection
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "",
      database: "tutorialtest"
    });

    Note:here you should enter your details for the database such as host, user, password etc.

  • Making the connection with previously created connection object
    con.connect(function(err){
      if(err){
        console.log('Error connecting to Db');
        return;
      }
      console.log('Connection established');
    });

    In the function the we pass to connect() function we can add things to happen in a successful or unsuccessful connection

  • Creating SQL query
    var queryString='SELECT * FROM tblstudents';

  • Passing SQL query and handling function to query() method
    con.query(queryString,function(err,rows){
      if(err) throw err;
      console.log('Data received from Db:\n');
      console.log(rows);
    });
    If the query successfully executed it will print the retrieved details otherwise error will be printed in the console

  • End the connection
    con.end();
Here is the complete code for Connecting to SQL database and retrieving data

var mysql = require("mysql");   //add mysql module

// create a connection object to the db
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "tutorialtest"
});

//connect to database using connection object
con.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});

//make the SQL quey
var queryString='SELECT * FROM tblstudents';

//execute the query
con.query(queryString,function(err,rows){
  if(err) throw err;

  console.log('Data received from Db:\n');
  console.log(rows);
});

//end the connection
con.end();

Please add a comment if you have some thing to add or something is not clear to you.


No comments:

Post a Comment