Languages
[Edit]
EN

Node.js - PostgreSQL Insert query

0 points
Created by:
Dirask JS Member
3460

In this article, we would like to show you how to make an SQL Insert query in Node.js.

Note: at the end of this article you can find database preparation SQL queries.

1. INSERT query example - async/await

const { Client } = require('pg');

const client = new Client({
    host: '127.0.0.1',
    user: 'postgres',
    database: 'database_name',
    password: 'password',
    port: 5432,
});

const insertUser = async (userName, userRole) => {
    try {
        await client.connect();           // gets connection
        await client.query(
            `INSERT INTO "users" ("name", "role")  
             VALUES ($1, $2)`, [userName, userRole]); // sends queries
        return true;
    } catch (error) {
        console.error(error.stack);
        return false;
    } finally {
        await client.end();               // closes connection
    }
};

insertUser('Matt', 'moderator').then(result => {
    if (result) {
        console.log('User inserted');
    }
});

Before:

[
    { id: 1, name: 'John',  role: 'admin' },     
    { id: 2, name: 'Chris', role: 'moderator' },
    { id: 3, name: 'Kate',  role: 'user' },      
    { id: 4, name: 'Denis', role: 'moderator' } 
]

After:

[
    { id: 1, name: 'John',  role: 'admin' },     
    { id: 2, name: 'Chris', role: 'moderator' },
    { id: 3, name: 'Kate',  role: 'user' },      
    { id: 4, name: 'Denis', role: 'moderator' }, 
    { id: 5, name: 'Matt',  role: 'moderator' } 
]

2. Database preparation

create_tables.sql file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(100) NOT NULL,
	"role" VARCHAR(15) NOT NULL,
	PRIMARY KEY ("id")
);

insert_data.sql file:

INSERT INTO "users"
	("name", "role")
VALUES
	('John', 'admin'),
	('Chris', 'moderator'),
	('Kate', 'user'),
	('Denis', 'moderator');

Node.js - PostgreSQL

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join