Node.js PG Package Tutorial šŸŽÆ

beginner
22 min

Node.js PG Package Tutorial šŸŽÆ

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! šŸ“

Getting Started šŸ’”

Before we begin, ensure you have Node.js installed on your machine, and create a new project directory.

bash
npm init -y

Next, install the pg package.

bash
npm install pg

Connecting to the Database šŸ’”

Now, let's write a simple script to connect to a PostgreSQL database.

javascript
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.

Querying the Database šŸ’”

Now that we're connected, let's learn how to execute queries.

javascript
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.

Manipulating Data šŸ’”

We can also use the pg package to manipulate data in our database.

javascript
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.

Handling Errors šŸ’”

It's essential to handle errors gracefully when working with databases.

javascript
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.

Quiz šŸ’”

Quick Quiz
Question 1 of 1

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! āœ