Welcome to our deep dive into the pg package, a popular choice for Node.js developers working with PostgreSQL databases. In this lesson, we'll explore how to connect, query, and manipulate data using this powerful tool. Let's get started! š
Before we begin, ensure you have Node.js installed on your machine, and create a new project directory.
npm init -yNext, install the pg package.
npm install pgNow, let's write a simple script to connect to a PostgreSQL database.
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
client.connect((err) => {
if (err) {
console.error('Error connecting to database', err);
return;
}
console.log('Connected to database');
});š” Pro Tip: Replace 'your_username', 'your_password', and 'your_database' with your actual PostgreSQL credentials.
Now that we're connected, let's learn how to execute queries.
const query = 'SELECT * FROM users';
client.query(query, (err, result) => {
if (err) {
console.error('Error executing query', err);
return;
}
console.log('Result', result.rows);
client.end();
});In this example, we execute a simple SELECT query and log the result.
We can also use the pg package to manipulate data in our database.
const insertQuery = 'INSERT INTO users (name, age) VALUES ($1, $2)';
const values = ['John Doe', 30];
client.query(insertQuery, values, (err, result) => {
if (err) {
console.error('Error inserting data', err);
return;
}
console.log('Data inserted successfully');
client.end();
});In this example, we insert a new user into the users table.
It's essential to handle errors gracefully when working with databases.
client.on('error', (err) => {
console.error('Unexpected error', err);
client.end();
});In this example, we set up an error handler to catch unexpected errors and gracefully close the connection.
What should be replaced in the connection string with your actual PostgreSQL credentials?
We hope you enjoyed learning about the pg package for Node.js. In the next lesson, we'll explore more advanced topics such as transactions, prepared statements, and more. Happy coding! ā