Skip to content

Connecting to a Database (Intro)

Programming Node.js Difficulty 1/5

Beginning of the lesson

Connecting to a Database

How a Node app remembers things after it stops

Big Idea: A normal variable forgets everything the moment your program ends. A database is a helper that stores your data safely on disk, so your Node app can write data now and read it back tomorrow.
By the end you will be able to:
  • 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.

Your app Node.js Database school.db query (SQL) rows (answer)
Your Node app sends a query through the driver; the database sends rows back.

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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers