Connecting a database
Data stored in a JavaScript array disappears when the server restarts. Real apps keep data in a database. This lesson uses SQLite through node:sqlite, a database built right into Node.js, and then shows how the same ideas apply to PostgreSQL and MongoDB.
SQLite, built in
SQLite stores a whole database in a single file (or in memory), with no separate server to install. Node 22.5+ includes it as node:sqlite:
| Method | Returns |
|---|---|
db.exec(sql) |
Nothing: runs one or more statements (creating tables) |
db.prepare(sql) |
A prepared statement you can run many times |
stmt.run(...params) |
{ changes, lastInsertRowid } for INSERT/UPDATE/DELETE |
stmt.get(...params) |
The first row as an object, or undefined |
stmt.all(...params) |
All rows as an array |
Rows come back as plain objects without a prototype, which is why Node prints them as [Object: null prototype]. They behave like normal objects.
If SQL is new to you, the SQL track on this site teaches it from scratch.
Never build SQL from strings
The ? placeholders are essential. Here's why:
That's SQL injection, one of the most common and most damaging security bugs. Always pass values as parameters. Named parameters (:email) make longer queries clearer:
db.prepare('UPDATE products SET price = :price WHERE id = :id').run({ id: 2, price: 9.49 });A CRUD API backed by the database
Here's an Express API where each route runs a query. The data-access functions live in their own module, so routes don't contain SQL:
Transactions
When several changes must succeed or fail together (moving money, placing an order), wrap them in a transaction:
Other databases
The pattern is the same for every database: install a driver, create a connection (or a pool of connections) once at startup, and run parameterised queries.
PostgreSQL with the pg package. Note that queries are asynchronous because the database is another server:
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const { rows } = await pool.query('SELECT * FROM products WHERE price < $1', [50]);
await pool.query('INSERT INTO products (name, price) VALUES ($1, $2)', ['Mug', 8.99]);MongoDB with the official mongodb driver:
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URL);
const products = client.db('shop').collection('products');
await products.insertOne({ name: 'Mug', price: 8.99, tags: ['kitchen'] });
const cheap = await products.find({ price: { $lt: 50 } }).toArray();ORMs and query builders
Many teams use a library that maps tables to JavaScript objects and generates SQL:
| Library | Style |
|---|---|
| Prisma | Schema file + generated, fully typed client (prisma.book.findMany()) |
| Drizzle | SQL-like TypeScript query builder |
| Kysely | Type-safe SQL query builder |
| Mongoose | Schemas and models for MongoDB |
They save typing and catch mistakes, but learn plain SQL first: every ORM eventually needs it.
Practice
- Add a
GET /books?author=…filter to the API using a parameterisedWHERE author = ?. - Add a
reviewstable (id,book_id,stars,text) and aPOST /books/:id/reviewsroute. - Write a
GET /statsroute that returns the number of books and the average year using a single SQL query.
1.Why use ? placeholders instead of putting values into the SQL string?
2.What does stmt.get() return when no row matches?
3.When do you need a transaction?