A student project needs a place to store records. Node.js includes a node:sqlite module that can create a SQLite database without adding a separate npm database package. In this lesson, you will insert two students and select one by score using prepared statements.
JavaScript value → Prepared SQL statement → SQLite table → Query result
Version and status
Use Node.js 26 for the code shown here. The module first appeared in earlier Node releases; it is currently marked as a release candidate in the Node 26 documentation. Its API may still change. The current class name is Database; older examples may show DatabaseSync, which Node 26 keeps as a deprecated alias.
Create the program
Create a folder, then save the following code as students.mjs. The :memory: database exists only while this program runs, so this practice example does not create a database file.
import { Database } from 'node:sqlite';
const database = new Database(':memory:');
try {
database.exec(`
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
score INTEGER NOT NULL
)
`);
const addStudent = database.prepare(
'INSERT INTO students (name, score) VALUES (?, ?)'
);
addStudent.run('Asha', 84);
addStudent.run('Ravi', 72);
const passingStudents = database.prepare(
'SELECT name, score FROM students WHERE score >= ? ORDER BY score DESC'
);
console.log(passingStudents.all(80));
} finally {
database.close();
}
Run node students.mjs. The result should contain one row: { name: 'Asha', score: 84 }. Ravi has a score below 80. The finally block closes the database even if a query fails.
Why use question marks?
The SQL contains ? placeholders, and values are passed separately to run or all. This keeps student input out of the SQL command text and is the right habit for queries that will later accept user-entered values. Do not build SQL by joining untrusted text into a string.
What about a real database file?
Replace ':memory:' with a path such as 'students.db' to keep records after the program ends. In that case, the program needs sensible file permissions, backups, and error handling. This synchronous API is easy for a small script; think about request concurrency before using it inside a busy web server.
Practice
- Add a third student with score 91 and predict the new output order.
- Change the threshold from 80 to 70 without changing the SQL text.
- Use a file database, run the program twice, and explain why a repeated insert may need a different design.
Continue with the Node.js learning path. Read the official Node.js SQLite documentation for current API status and more methods.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.