fetch data from postgresql in javascript

To fetch data from PostgreSQL in Javascript, we need to use the pg module which is a PostgreSQL client for Node.js. Here are the steps to fetch data:

  1. First, we need to install the pg module using npm:
index.tsx
npm install pg
15 chars
2 lines
  1. After that, we need to create a new client instance of the pg module and define the database connection details:
index.tsx
const { Client } = require('pg');

const client = new Client({
  user: 'username',
  password: 'password',
  host: 'localhost',
  port: 5432,
  database: 'mydatabase'
});

client.connect();
190 chars
12 lines
  1. Now, we can use the client instance to execute SQL queries and fetch data. For example, to fetch all rows from a table, we can use the client.query() method like this:
index.tsx
client.query('SELECT * FROM mytable', (err, res) => {
  if (err) throw err;
  console.log(res.rows);
  client.end();
});
121 chars
6 lines

This will execute the SQL query and return the result in the res object. We can access the rows of the result using res.rows.

  1. Finally, we need to close the client connection using the client.end() method.

Note: It's important to handle errors properly, and make sure to end the client connection when finished to free up resources.

gistlibby LogSnag