← Runnable Projects

阅读中文版本

In-Memory SQLite Demo

A Node script that opens an in-memory SQLite database using the built-in node:sqlite module, creates a table, inserts rows, and queries them back.

beginnerjavascriptunverified

Project

node-sqlite-memory

Entry point: sqlite-demo.mjs

Install

node --version

Run

node sqlite-demo.mjs

Test

node --test sqlite-demo.test.mjs

Expected output

Prints the rows inserted into the in-memory database, demonstrating create, insert, and select.

Dependencies

  • node >=22

What it does

Demonstrates the built-in SQLite module with an in-memory database, so no native dependency and no database file are required.

import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync(':memory:');
db.exec('CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)');

const insert = db.prepare('INSERT INTO notes (body) VALUES (?)');
insert.run('first note');
insert.run('second note');

const rows = db.prepare('SELECT id, body FROM notes ORDER BY id').all();
for (const row of rows) console.log(row.id + ': ' + row.body);
console.log('count=' + rows.length);
db.close();

The script creates a table, inserts parameterised rows, and selects them back, which covers the three operations most scripts need.

Run and verify

node sqlite-demo.mjs

Run with Node 22 or later, where node:sqlite is available without a flag in current releases.

Expected Output

The program should print the two inserted rows and a count. The console.log output is:

1: first note
2: second note
count=2

Rows come back in id order, the sequential ids start at one, and closing the database releases the in-memory store.

Limitations

The database lives only for the process; to persist, pass a file path instead of :memory: and manage the file on disk.