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.
xxxxxxxxxx
1
npm install pg
Step 2 - Import the pg
module by using require and create a connection with the PostgreSQL database.
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
database: 'database_name',
7
password: 'password',
8
port: 5432,
9
});
10
11
const execute = async () => {
12
try {
13
await client.connect(); // gets connection with database
14
console.log('database connected'); // sends queries
15
} catch (error) {
16
console.log(error.stack);
17
} finally {
18
await client.end(); // closes connection
19
}
20
};
21
22
execute();
That's it, you've been connected and from now on you can query your database.
- with async/await
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
database: 'my_database',
7
password: 'password',
8
port: 5432,
9
});
10
11
const execute = async () => {
12
try {
13
await client.connect(); // gets connection
14
const response = await client.query('SELECT * FROM users'); // sends queries
15
console.log(response.rows);
16
} catch (error) {
17
console.log(error.stack);
18
} finally {
19
await client.end(); // closes connection
20
}
21
};
22
23
execute();
- with promises
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
database: 'database_name',
7
password: 'password',
8
port: 5432,
9
});
10
11
client
12
.connect() // gets connection
13
.then(() => console.log('database connected'))
14
.catch((error) => console.error('connection error', error.stack))
15
.then(() => client.query('SELECT * FROM users')) // sends queries
16
.then((result) => console.log(JSON.stringify(result.rows, null, 4)))
17
.catch((error) => console.error('query error', error.stack))
18
.finally(() => client.end()); // closes connection