EN
Node.js - PostgreSQL Drop table
3 points
In this article, we would like to show you how to delete 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 deleteTable = async () => {
12
try {
13
await client.connect(); // gets connection
14
await client.query('DROP TABLE "users"'); // 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
deleteTable().then((result) => {
25
if (result) {
26
console.log('Table deleted');
27
}
28
});
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(100) NOT NULL,
4
"role" VARCHAR(15) NOT NULL,
5
PRIMARY KEY ("id")
6
);