Node.js

PostgreSQL integration

Connect To PostgreSQL

Using PostgreSQLnpm module.

install dependency from npm

npm  install pg --save

Now you have to create a PostgreSQL connection, which you can later query.

Assume you Database_Name = students, Host = localhost and DB_User= postgres

var pg = require("pg")
var connectionString = "pg://postgres:postgres@localhost:5432/students";
var client = new pg.Client(connectionString);
client.connect();

Query with Connection Object

If you want to use connection object for query database you can use this sample code.

var queryString = "SELECT name, age FROM students " ;
var query = client.query(queryString);

query.on("row", (row, result)=> {
result.addRow(row);
});

query.on("end", function (result) {
//LOGIC
});

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow