Node.js Database Connectivity with Postgresql

PostgreSQL is a Powerful,Open Source object-Relational(Relational Database with Object Oriented Feature) database System.PostgreSQL runs on all major operating systems like Linux,Unix,Windows etc.

During Connection with PostgreSQL at first we install pg Package and to install this package we use this command.


npm install pg

Note : If you have install Latest version of Node.js then there is no problem but if it is old version.then at first install npm package for this purpose use this command.


npm install

After installing this package we follow these five steps for database connection as discussed below :
During Database connction we have to follow these 5 steps

  1. Import Packages
  2. Open a Connection
  3. Execute Query
  4. Extract Data
  5. CleanUp the Environment

Import Packages


var pg = require("pg");

Open a Connection


var connectString = "pg://postgres:root_123@localhost:5432/NewDatabase";
/*
 pg              :< package >
        postgres        :< PostgreSQL UserName >
        root_123        :< PostgreSQL password >
        @localhost:5432 :< host Name >
        NewDatabase     :< database Name >
*/

var client = new pg.Client(connectString);

client.connect();

Execute Query


var executeQuery = client.query("SELECT * FROM public.attendanceremark;");

Extract Data


executeQuery .on("end", function (result) {

    console.log(JSON.stringify(result.rows, null, "    ")); //Gives OutPut in JSONString format

    var details=JSON.stringify(result.rows, null, "    "); 


    var emp=JSON.parse(details);                 //Parse JSONString to JSON Format

   for(var i=0;i<emp.length;i++){

    console.log(":::::::: "+emp[i].empname+ " ********** " +emp[i].remarkid);
   // empname and remarkid are attributes of attendanceremark table
  }

cleanUP Environment


  client.end();

});

Hence our complete code


var pg = require("pg");

var connectString = "pg://postgres:root_123@localhost:5432/NewDatabase";
/*
 pg              :< package >
        postgres        :< PostgreSQL UserName >
        root_123        :< PostgreSQL password >
        @localhost:5432 :< host Name >
        NewDatabase     :< database Name >
*/

var client = new pg.Client(connectString);

client.connect();

var executeQuery = client.query("SELECT * FROM public.attendanceremark;");

executeQuery .on("end", function (result) {

    console.log(JSON.stringify(result.rows, null, "    ")); //Gives OutPut in JSONString format

    var details=JSON.stringify(result.rows, null, "    "); 


    var emp=JSON.parse(details);                 //Parse JSONString to JSON Format

for(var i=0;i<emp.length;i++){

    console.log(":::::::: "+emp[i].empname+ " ********** " +emp[i].remarkid);
// empname and remarkid are attributes of attendanceremark table
 }

Leave a Reply

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