EN
Node.js - PostgreSQL Create table
0 points
In this article, we would like to show you how to create a table in Node.js.
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 (query) => {
12
try {
13
await client.connect(); // gets connection
14
await client.query(query); // sends queries
15
return true;
16
} catch (error) {
17
console.error(error.stack);
18
return false;
19
} finally {
20
await client.end(); // closes connection
21
}
22
};
23
24
const text = `CREATE TABLE "users" (
25
"id" SERIAL,
26
"name" VARCHAR(100) NOT NULL,
27
"role" VARCHAR(15) NOT NULL,
28
PRIMARY KEY ("id")
29
);`;
30
31
execute(text).then(result => {
32
if (result) {
33
console.log('Table created');
34
}
35
});
Database:

Note:
To create a multi-line string, create a
template literal
usingbackticks
``
.