EN
Node.js - how to connect with PostgreSQL
0
points
In this article, we would like to show you how to use PostgreSQL in Node.js.
Step 1 - Install the node-postgres
module in your Node project.
npm install pg
Step 2 - Import the pg
module by using require and create a connection with the PostgreSQL database.
const { Client } = require('pg');
const client = new Client({
host: '127.0.0.1',
user: 'postgres',
database: 'database_name',
password: 'password',
port: 5432,
});
const execute = async () => {
try {
await client.connect(); // gets connection with database
console.log('database connected'); // sends queries
} catch (error) {
console.log(error.stack);
} finally {
await client.end(); // closes connection
}
};
execute();
That's it, you've been connected and from now on you can query your database.
Practical example with SELECT query:
- with async/await
const { Client } = require('pg');
const client = new Client({
host: '127.0.0.1',
user: 'postgres',
database: 'my_database',
password: 'password',
port: 5432,
});
const execute = async () => {
try {
await client.connect(); // gets connection
const response = await client.query('SELECT * FROM users'); // sends queries
console.log(response.rows);
} catch (error) {
console.log(error.stack);
} finally {
await client.end(); // closes connection
}
};
execute();
- with promises
const { Client } = require('pg');
const client = new Client({
host: '127.0.0.1',
user: 'postgres',
database: 'database_name',
password: 'password',
port: 5432,
});
client
.connect() // gets connection
.then(() => console.log('database connected'))
.catch((error) => console.error('connection error', error.stack))
.then(() => client.query('SELECT * FROM users')) // sends queries
.then((result) => console.log(JSON.stringify(result.rows, null, 4)))
.catch((error) => console.error('query error', error.stack))
.finally(() => client.end()); // closes connection