Skip to content

pg node postgres

Daisho Komiyama edited this page Dec 28, 2022 · 3 revisions

npm: https://www.npmjs.com/package/pg
documentation: https://node-postgres.com/
guide: https://sql.holt.courses/lessons/data/nodejs-and-postgresql

Connecting to a database

const pg = require("pg");
const pool = new pg.Pool({
  user: "postgres",
  host: "localhost",
  database: "recipeguru",
  password: "lol",
  port: 5432,
});

Notes:

  • These are the default credentials combined with what I set up in the previous lessons. Make sure you're using the correct credentials.
  • Make sure you started PostgreSQL via docker with the -p 5432:5432 flag, or PostgreSQL won't be exposed on your host system.
  • Make sure your database is running too.
  • Once you've done this, you can start making queries to PostgreSQL!

Let's write a query.

const { rows } = await pool.query(`SELECT * FROM recipes`);

Parameterization and SQL injection

Don't do this.

const { id } = req.query;
const { rows } = await pool.query(`SELECT * FROM ingredients WHERE id=${id}`); // 😱

xkcd comic

How we sanitize user input

const { id } = req.query;
const { rows } = await pool.query(`SELECT * FROM ingredients WHERE id=$1`, [id]);
Clone this wiki locally