How to Connect PostgreSQL with Nodejs
Connect your database server with nodejs in just a seconds.
In this tutorial, we will learn how to "Connect Postgresql database with Nodejs".
Prerequisite
Before we get started, make sure all these technologies are installed on your local machine.
Nodejs v+ 18 already installed,
PostgreSQL Driver already installed;
Sample Project
In our sample project, we will build a simple database store that has the names of employees and salary range;
Create a new database collection
Create a new database
CREATE DATABASE organisation;
Check if the database is created
\l
Connect to the database
\c organisation;
Create a data collection of employee
CREATE TABLE employee ( emp_id INT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, gender CHAR(1), birthdate DATE, email VARCHAR(100) UNIQUE, salary INT );
To check whether the employee table is created.
\d employee;
Insert Table
Insert table is used for adding rows of data into the database. Now let's insert the data into your database, if you check your table using \d employee
you would notice that the row and column of the table are empty.
INSERT INTO employee(emp_id, first_name, last_name, gender, birthdate, email, salary)
VALUES(1,'Annie','Smith','M', DATE '1988-01-09', 'emma@email.com',5000);
SELECT
SELECT will list all the data available in the employee table.
SELECT * FROM employee;
Create Our Nodejs App
Let's connect our Nodejs app to our PostgreSQL database. For more find the GitHub repository here: https://github.com/EmmaUmeh/NodePostgresql
Initialize your Nodejs project
npm init --y
Install PostgreSQL database dependency
npm install pg
Create a
databasepostgres.js
fileconst {Client} = require('pg'); const client = new Client({ host: "localhost", user: "postgres", //default PostgreSQL username port: 5432, //default PostgreSQL port number password: "*****", //default PostgreSQL password database: "postgres" }) client.connect(); //connect() connects our database client.query('SELECT * FROM employee', (err, res) => { return(!err) ? console.log(res.rows) : console.log(err.message); })
Now let's run this to check whether it is connected.
node databasepostgres
In the terminal console, you would see the database running.
Conclusion
Furthermore, we have connected a simple database store using nodejs, what other technologies would you like to use in the future for your project, Let's us know in our comment section.