Using SQLite3 Package for SQLite Database Management in Node.js
"To use SQLite with Node.js, the sqlite3 library is a commonly used package. The sqlite3 package is a lightweight library that provides a straightforward API for interacting with SQLite databases from within a Node.js application.
Installation:
First, you need to install the sqlite3 package. You can do this using npm (Node Package Manager):
npm install sqlite3
Basic Usage:
Here’s a quick example of how to use SQLite in a Node.js application:
const sqlite3 = require('sqlite3').verbose();
// Connect to a database (or create one if it doesn’t exist)
let db = new sqlite3.Database('example.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the example.db SQLite database.');
});
// Create a table
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL
)`, (err) => {
if (err) {
console.error(err.message);
}
console.log('Created users table.');
});
// Insert data into the table
let insert = 'INSERT INTO users (name, age) VALUES (?, ?)';
db.run(insert, ['Alice', 30], function (err) {
if (err) {
console.error(err.message);
}
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
db.run(insert, ['Bob', 25], function (err) {
if (err) {
console.error(err.message);
}
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
// Query the data
db.all(`SELECT * FROM users`, [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row);
});
});
// Close the database
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Closed the database connection.');
});
Explanation:
-
Connect to the Database: The
sqlite3.Databasemethod is used to connect to the SQLite database specified, or create it if it does not exist. -
Create a Table: The
db.runmethod executes an SQL command to create a table namedusersif it does not already exist. -
Insert Data: The
db.runmethod is used again to insert data into theuserstable, using prepared statements (?placeholders). -
Query Data: The
db.allmethod is used to run an SQLSELECTquery that retrieves all rows from theuserstable and logs them to the console. -
Close the Database: The
db.closemethod closes the database connection.
Notes:
- Error Handling: Always include error handling to catch and manage any issues that may occur when interacting with the database.
- Prepared Statements: Using placeholders (
?) in the SQL statements helps prevent SQL injection attacks. - Asynchronous Operations: All SQLite database operations are asynchronous, and you can use callbacks to handle the results and next steps.
By integrating SQLite with Node.js, developers can create lightweight, local databases for applications like simple web servers, desktop apps, and more. The sqlite3 package offers a simplistic yet powerful way to interact with SQLite databases in a Node.js environment."