Node.js with Postgres DB and table row
Here’s how to create a table named Employee, insert three records, and connect to your mydb database in PostgreSQL using Node.js
const { Client } = require('pg');
async function main() {
// Connection configuration
const config = {
host: "localhost",
user: "postgres", // Replace with your PostgreSQL username
password: "admin", // Replace with your PostgreSQL password
database: "mydb", // Connect directly to the 'mydb' database
port: 5432, // Default PostgreSQL port
};
const client = new Client(config);
try {
// Connect to PostgreSQL
await client.connect();
console.log("Connected to PostgreSQL!");
// Create Employee table
const createTableQuery = `
CREATE TABLE IF NOT EXISTS Employee (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
age INTEGER,
department VARCHAR(50)
);
`;
await client.query(createTableQuery);
console.log("Table 'Employee' created successfully.");
// Insert records into Employee table
const insertQuery = `
INSERT INTO Employee (name, age, department)
VALUES
('Alice', 30, 'HR'),
('Bob', 25, 'IT'),
('Charlie', 35, 'Finance');
`;
await client.query(insertQuery);
console.log("3 records inserted into 'Employee' table.");
// Fetch and display records
const selectQuery = `SELECT * FROM Employee;`;
const result = await client.query(selectQuery);
console.log("Employee Records:");
result.rows.forEach((row) => {
console.log(row);
});
} catch (err) {
console.error("Error:", err.message);
} finally {
// Disconnect the client
await client.end();
console.log("Disconnected from PostgreSQL.");
}
}
// Run the main function
main();
Terminal Commands and logs
PS D:\React_Project\NodeProject> node NodeJsDBTableRowExample.js
Connected to PostgreSQL!
Table 'Employee' created successfully.
3 records inserted into 'Employee' table.
Employee Records:
{ id: 1, name: 'Alice', age: 30, department: 'HR' }
{ id: 2, name: 'Bob', age: 25, department: 'IT' }
{ id: 3, name: 'Charlie', age: 35, department: 'Finance' }
Disconnected from PostgreSQL.
PS D:\React_Project\NodeProject>
Recent Comments