Part 3.3 of Databases for beginners - PostgreSQL and Node.JS

By Lovisa Johansson - posted Part 3.3 of Databases for beginners - PostgreSQL and Node.JS

Part 3 of Databases for beginners show how to connect to your database via Node.js.

Our previous article explained the SQL language. We executed some standard SQL queries from the web browser, and it's time to show how to do this programmatically, and how to use your database in combination with your application. Our first article also showed how to create a database for free, in the cloud. In this part of the series we show how to connect to your database via Node.js.

Node.js and PostgreSQL

A client library for PostgreSQL has to be downloaded. A client library has several methods that can be used, in this case to communicate with PostgreSQL. The methods should be used when you, for example, connect to the database (using the given parameters, host name, port number, etc) or when you select data from your database. There is a choice of libraries for almost every programming language.

Our recommended way to connect to PostgreSQL is via the client node-postgres. Install it by running npm install pg.

var pg = require('pg');
//or native libpq bindings
//var pg = require('pg').native

var conString = process.env.ELEPHANTSQL_URL || "postgres://postgres:5432@localhost/postgres";

var client = new pg.Client(conString);
client.connect(function(err) {
  if(err) {
    return console.error('could not connect to postgres', err);
  }
  client.query('SELECT NOW() AS "theTime"', function(err, result) {
    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].theTime);
    //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
    client.end();
  });
});

If you have any questions, comments or need feedback, please do not hesitate to contact us at support@elephantsql.com .