Databases: SQL with Node
Talk to Postgres and MySQL from Node.js — safely, with parameterized queries
async/await, and — most importantly — pass user input through parameterized statements so an attacker can never rewrite your SQL.
- choose and install a database driver (
pgfor Postgres,mysql2for MySQL), - open a connection with a connection pool and read a connection string,
- run
SELECT,INSERT,UPDATEqueries and read the result rows, - use parameterized queries to stop SQL injection,
- handle errors and release connections correctly.
1. Why a database (and not a file)?
In the beginner course you saved data with the fs module — reading and writing JSON files. That works for a to-do list on your laptop, but it falls apart when a real app needs to: search millions of rows quickly, let dozens of requests write at the same time without corrupting the file, and guarantee that a half-finished update never leaves data in a broken state.
A relational database (Postgres, MySQL, SQLite) solves all three. It stores data in tables — rows and columns with types — and you talk to it in SQL (Structured Query Language). Node does not speak SQL by itself; you install a driver, a small library that opens a network connection to the database and turns your query text plus JavaScript values into the wire protocol the database understands.
Analogy. The database is a huge, well-organized warehouse. SQL is the order form you fill in ("give me every customer in Berlin"). The driver is the courier who carries your order to the warehouse and brings the boxes back. You never walk into the warehouse yourself — you always work through the courier.