Web Development · Advanced level

Advanced level · Module 1: Databases for Web Applications · Lesson 2 of 4

Querying from Node.js Safely

Connect to a database from Express and run parameterised queries for create, read, update and delete.

In this lesson you will

  • Connect to a database from Node.js
  • Write parameterised queries for CRUD operations

Key concepts

database driverconnection poolparameterised querySQL injection

The lesson

A database driver connects Node.js to the database. For PostgreSQL, a connection pool reuses connections efficiently; SQLite opens a file directly. Keep the connection string in an environment variable.

Always pass values as parameters: db.query("SELECT * FROM bookings WHERE customer_id = $1", [id]). Building SQL by joining strings lets attackers inject SQL — one of the most damaging web vulnerabilities.

Map query results to the JSON your API returns and handle 'not found' explicitly with 404.

Step by step

  1. Connect the API to the database.
  2. Rewrite the course endpoints with SQL queries.
  3. Use parameters for every value.
  4. Show that an injection attempt fails.

Practice activity

Move every training centre endpoint from the JSON file to the database.

Expected result: All endpoints work from the database and every query is parameterised.

Check your understanding

  1. Why use a connection pool?

    Show answer

    It reuses connections, which is faster than opening one per request.

  2. How do parameterised queries prevent SQL injection?

    Show answer

    Values are sent separately from the SQL, so they are never run as SQL.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.