To connect a PostgreSQL database with Node.js, you can use the pg
package, which is a popular client for PostgreSQL in Node.js.
Steps to Connect PostgreSQL to Node.js:
- Install the
pg
Package
Use npm to install thepg
module.npm install pg
- Set Up Connection to PostgreSQL
Use theClient
class to establish a connection.
Example Code:
// Step 1: Import the pg module
const { Client } = require('pg');
// Step 2: Create a new PostgreSQL client
const client = new Client({
host: 'localhost', // Database host
user: 'your_username', // Database username
password: 'your_password', // Database password
database: 'your_db_name', // Database name
port: 5432, // Default PostgreSQL port
});
// Step 3: Connect to the database
client.connect()
.then(() => console.log('Connected to PostgreSQL'))
.catch(err => console.error('Connection error', err.stack));
// Step 4: Query the database
client.query('SELECT * FROM your_table_name', (err, res) => {
if (err) {
console.error('Error executing query', err.stack);
} else {
console.log('Query results:', res.rows);
}
// Step 5: Close the connection
client.end();
});
Key Points:
- Connection Parameters:
host
: The PostgreSQL server (usuallylocalhost
for local development).user
: Your PostgreSQL username.password
: Your PostgreSQL password.database
: The name of the database.port
: Default PostgreSQL port is5432
.
- Connecting:
client.connect()
establishes the connection.- Handle success or errors using
.then()
or.catch()
.
- Querying:
client.query()
executes SQL queries. Replace'SELECT * FROM your_table_name'
with your desired query.- Results are returned in
res.rows
, which contains the fetched data.
- Closing Connection:
- Use
client.end()
to close the database connection.
- Use
Output Example:
If the table contains data, the output in the terminal would look like:
Connected to PostgreSQL
Query results: [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' } ]
Alternative: Use Pool
for Connection Pooling
If your app requires multiple queries and connections, use Pool
instead of Client
for better performance.
const { Pool } = require('pg');
const pool = new Pool({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_db_name',
port: 5432,
});
pool.query('SELECT * FROM your_table_name', (err, res) => {
if (err) {
console.error('Error executing query', err.stack);
} else {
console.log('Query results:', res.rows);
}
pool.end();
});
By following these steps, you can successfully connect and interact with a PostgreSQL database in a Node.js application.