1//connect to postgres database in node
2
3const Pool = require('pg').Pool;
4
5const pool = new Pool({
6 user: '',
7 host: 'localhost',
8 database: '',
9 password: '',
10 port:5432,
11 })
12
13//query example
14
15app.get('/users',async(req,res)=>{
16
17 try{
18 let resp=await pool.query('SELECT * FROM users');
19 }catch(err){
20 res.status(200).send(resp.rows);
21 }
22})
23
24
1//connect to postgres database in node
2
3const Pool = require('pg').Pool;
4
5const pool = new Pool({
6 user: '',
7 host: 'localhost',
8 database: '',
9 password: '',
10 port:5432,
11 })
12
13//query example
14
15app.get('/users',async(req,res)=>{
16
17 try{
18 let resp=await pool.query('SELECT * FROM users');
19 }catch(err){
20 res.status(200).send(resp.rows);
21 }
22})
23
1// callback
2client.query('SELECT NOW() as now', (err, res) => {
3 if (err) {
4 console.log(err.stack)
5 } else {
6 console.log(res.rows[0])
7 }
8})
9// promise
10client
11 .query('SELECT NOW() as now')
12 .then(res => console.log(res.rows[0]))
13 .catch(e => console.error(e.stack))
1const { Client } = require('pg')const client = new Client();(async () => { await client.connect() const res = await client.query('SELECT $1::text as message', ['Hello world!']) console.log(res.rows[0].message) // Hello world! await client.end()})()