← Level 4 – Data pro

Lesson 4 of 6 ⏱ 45 minutes Premium

SQLite – a database in a single file

Install SQLite in Node.js and save your first row into a table.

What SQLite is

SQLite is a database stored in a single file (e.g. web.db). You don’t need to install any big server – ideal for learning and smaller projects. Data in it survives a Node.js restart.

In Node.js we’ll use the better-sqlite3 package:

cd my-server
npm install better-sqlite3

Show me: a table and the first record

In server.js (or a new database.js that you import):

const Database = require("better-sqlite3");
const db = new Database("web.db");

// Create the table if it doesn't exist yet
db.exec(`
  CREATE TABLE IF NOT EXISTS vzkazy (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    jmeno TEXT NOT NULL,
    text TEXT NOT NULL,
    vytvoreno TEXT DEFAULT CURRENT_TIMESTAMP
  )
`);

// Insert one row
const vloz = db.prepare("INSERT INTO vzkazy (jmeno, text) VALUES (?, ?)");
vloz.run("Martin", "First message in the database! 🎉");

// Read all rows
const vse = db.prepare("SELECT * FROM vzkazy").all();
console.log(vse);

Run node server.js (or a short test script). You’ll see an array of objects in the console. A file called web.db appears in your project folder – that’s the entire database.

💡

SQL in a nutshell: CREATE TABLE = a new table (like a sheet in Excel). INSERT = add a row. SELECT = read data. The question marks ? in prepare protect against SQL injection – never insert user text directly into a query string!

Your turn 💪

  1. Install better-sqlite3 in your server folder.
  2. Create a vzkazy table following the example (columns: id, jmeno, text, vytvoreno).
  3. Insert 3 test messages using INSERT.
  4. Stop the script, run it again, and SELECT once more – is the data still there?
  5. Add web.db to .gitignore (in production, every server has its own database; sometimes it’s exported separately).

Check: The file web.db exists, and data remains after a restart. In the next lesson we’ll connect the whole guestbook to it through an API.

What to take away from this lesson