Connecting to a Database
How a Node app remembers things after it stops
- say why a Node app needs a database instead of just variables,
- do a simple write and read with real code,
- read a connection string and keep it safe (no secrets in your code).
1. Why not just use variables?
You already know how to store a value in a variable. But variables live only in memory while the program runs. When the program stops, that memory is cleared and the value is gone. Try this little program and run it twice:
// counter.js -- run it, stop it, run it AGAIN
let visits = 0;
visits = visits + 1;
console.log('Visits so far:', visits);
$ node counter.js
Visits so far: 1
$ node counter.js
Visits so far: 1 <-- it forgot! the variable starts at 0 every run
It always prints 1, never 2. The variable cannot remember the last run. A database fixes this: it saves your data to disk so it is still there next time. Think of it as a notebook that never forgets, while a variable is like writing on your hand and then washing it.
2. How your app talks to a database
Your Node code does not touch the database files directly. Instead it uses a small library called a driver (for example better-sqlite3, mysql2, or pg). You send the database a query (a request written in a language called SQL), and the database sends back rows (the answer). It is a simple request → response.
A table is like a spreadsheet: it has columns (such as id and name) and rows (one per student). You write data with INSERT and you read data with SELECT.