Step-by-Step Guide: Integrating SQLite with a Node.js Application
Integrating SQLite with a Node.js application can be straightforward using the sqlite3 module. Here's a guide on how to set up and use SQLite in a Node.js project:
-
Install Dependencies: First, you need to create a new Node.js project and install the
sqlite3package.mkdir my-sqlite-app cd my-sqlite-app npm init -y npm install sqlite3 -
Create a Database and Table: Create a new file named
app.jsand write the following code to create a SQLite database and a table.const sqlite3 = require('sqlite3').verbose(); const db = new sqlite3.Database(':memory:'); db.serialize(() => { // Create a new table db.run("CREATE TABLE user (id INT, name TEXT)"); // Insert a row into the table const stmt = db.prepare("INSERT INTO user VALUES (?, ?)"); stmt.run(1, "John Doe"); stmt.finalize(); // Query the table db.each("SELECT id, name FROM user", (err, row) => { if (err) { console.error(err.message); } console.log(`User ID: ${row.id}, Name: ${row.name}`); }); }); // Close the database connection db.close((err) => { if (err) { console.error(err.message); } console.log('Database connection closed.'); }); -
Run Your Application: Save
app.jsand run your application using Node.js.node app.jsYou should see output similar to:
User ID: 1, Name: John Doe Database connection closed. -
Using a Persistent Database: Instead of using an in-memory database (
:memory:), you can specify a file to store the database persistently.const db = new sqlite3.Database('./my-database.db'); db.serialize(() => { db.run("CREATE TABLE IF NOT EXISTS user (id INT, name TEXT)"); const stmt = db.prepare("INSERT INTO user VALUES (?, ?)"); stmt.run(1, "John Doe"); stmt.finalize(); db.each("SELECT id, name FROM user", (err, row) => { if (err) { console.error(err.message); } console.log(`User ID: ${row.id}, Name: ${row.name}`); }); }); db.close((err) => { if (err) { console.error(err.message); } console.log('Database connection closed.'); }); -
Handling Async Operations: SQLite operations can also be handled asynchronously using promises or callback functions. Here’s an example of using promises:
const sqlite3 = require('sqlite3').verbose(); const { open } = require('sqlite'); const dbPromise = open({ filename: './my-database.db', driver: sqlite3.Database }); (async () => { const db = await dbPromise; await db.exec("CREATE TABLE IF NOT EXISTS user (id INT, name TEXT)"); await db.run("INSERT INTO user VALUES (?, ?)", [2, "Jane Doe"]); const rows = await db.all("SELECT id, name FROM user"); rows.forEach((row) => { console.log(`User ID: ${row.id}, Name: ${row.name}`); }); await db.close(); console.log('Database connection closed.'); })().catch((err) => { console.error(err); }); -
Query Examples: Some common query patterns are as follows:
Insert Data:
db.run("INSERT INTO user (id, name) VALUES (?, ?)", [1, 'John Doe'], function(err) { if (err) { return console.error(err.message); } console.log(`A row has been inserted with rowid ${this.lastID}`); });Select Data:
db.all("SELECT id, name FROM user", [], (err, rows) => { if (err) { throw err; } rows.forEach((row) => { console.log(row.name); }); });Update Data:
db.run(`UPDATE user SET name = ? WHERE id = ?`, ['Jane Doe', 1], function(err) { if (err) { return console.error(err.message); } console.log(`Row(s) updated: ${this.changes}`); });Delete Data:
db.run(`DELETE FROM user WHERE id = ?`, 1, function(err) { if (err) { return console.error(err.message); } console.log(`Row(s) deleted ${this.changes}`); });
These examples should help you get started with integrating SQLite in your Node.js application. For more advanced usage, you can refer to the SQLite3 documentation and the sqlite3 Node.js package documentation.