Home

Using SQLite3 Package for SQLite Database Management in Node.js

27 views

"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:

  1. Connect to the Database: The sqlite3.Database method is used to connect to the SQLite database specified, or create it if it does not exist.

  2. Create a Table: The db.run method executes an SQL command to create a table named users if it does not already exist.

  3. Insert Data: The db.run method is used again to insert data into the users table, using prepared statements (? placeholders).

  4. Query Data: The db.all method is used to run an SQL SELECT query that retrieves all rows from the users table and logs them to the console.

  5. Close the Database: The db.close method 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."