A Beginner's Guide to Using SQLite in a JavaScript/Node.js Application

In this guide, we will explore the basics of using SQLite in a JavaScript/Node.js application, including installation, setup, and common database operations.

Posted on

SQLite is a lightweight, serverless, and self-contained SQL database engine that is widely used for building applications that require local data storage. In this guide, we will explore the basics of using SQLite in a JavaScript/Node.js application, including installation, setup, and common database operations.

Prerequisites

Before we begin, ensure you have the following prerequisites in place:

  1. Node.js: Make sure you have Node.js installed on your system. You can download it from nodejs.org.

  2. SQLite: SQLite comes pre-installed with most operating systems. If it’s not installed on your system, you can download it from the SQLite website.

  3. SQLite Node.js Library: You’ll need a Node.js library to interact with SQLite. One commonly used library is sqlite3. Install it using npm:

    npm install sqlite3
    

Creating an SQLite Database

To start using SQLite in your JavaScript/Node.js application, you first need to create an SQLite database. You can create a database file using the SQLite command-line tool or programmatically in your Node.js application.

Command-Line

Open your terminal and run the following command to create a new SQLite database file (e.g., mydatabase.db):

sqlite3 mydatabase.db

This will open the SQLite shell for the newly created database. You can execute SQL commands from here. To exit the shell, type .exit.

Programmatically

In your JavaScript/Node.js application, you can create an SQLite database using the sqlite3 library like this:

const sqlite3 = require("sqlite3").verbose()
const db = new sqlite3.Database("mydatabase.db")

// Close the database when done
db.close()

This code creates a new SQLite database file named mydatabase.db in your application’s directory.

Performing Basic Database Operations

SQLite allows you to perform various database operations, including creating tables, querying, inserting, updating, and deleting data. Let’s look at some examples:

Creating a Table

// Introduction: Creating a 'users' table.
const db = new sqlite3.Database("mydatabase.db")

db.serialize(() => {
  db.run(
    "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, email TEXT)"
  )

  console.log("Table created successfully!")

  // Close the database when done
  db.close()
})

This code creates a new table named ‘users’ with three columns: ‘id,’ ‘username,’ and ’email.’

Inserting Data

// Introduction: Adding a new user to the 'users' table.
const db = new sqlite3.Database("mydatabase.db")

db.serialize(() => {
  const stmt = db.prepare("INSERT INTO users (username, email) VALUES (?, ?)")
  stmt.run("john_doe", "[email protected]")
  stmt.finalize()

  console.log("Data inserted successfully!")

  // Close the database when done
  db.close()
})

After executing this code, a new user record will be added to the ‘users’ table.

Querying Data

// Introduction: Fetching data from the 'users' table.
const db = new sqlite3.Database("mydatabase.db")

db.serialize(() => {
  db.all("SELECT * FROM users", (err, rows) => {
    if (err) {
      console.error("Error querying data:", err)
      return
    }

    console.log("Query results:", rows)
  })

  // Close the database when done
  db.close()
})

Running this code retrieves all records from the ‘users’ table and logs the results.

Updating Data

// Introduction: Updating a user's email in the 'users' table.
const db = new sqlite3.Database("mydatabase.db")

db.serialize(() => {
  db.run(
    "UPDATE users SET email = ? WHERE username = ?",
    ["[email protected]", "john_doe"],
    (err) => {
      if (err) {
        console.error("Error updating data:", err)
        return
      }

      console.log("Data updated successfully!")
    }
  )

  // Close the database when done
  db.close()
})

Using the UPDATE query, you can modify specific fields within a record.

Deleting Data

// Introduction: Deleting a user record from the 'users' table.
const db = new sqlite3.Database("mydatabase.db")

db.serialize(() => {
  db.run("DELETE FROM users WHERE username = ?", ["john_doe"], (err) => {
    if (err) {
      console.error("Error deleting data:", err)
      return
    }

    console.log("Data deleted successfully!")
  })

  // Close the database when done
  db.close()
})

The DELETE FROM query removes a specific user record from the ‘users’ table.

Handling Errors

Proper error handling is crucial in any production application, especially when interacting with databases

. Be sure to handle errors gracefully to maintain the stability and reliability of your Node.js application.

Conclusion

SQLite is an excellent choice for small to medium-sized applications that require local data storage. In this guide, we covered the basics of using SQLite in a JavaScript/Node.js application, from creating a database to performing common database operations. As you become more proficient with SQLite, you can explore its advanced features and optimizations to build lightweight and efficient data-driven applications. With SQLite and Node.js, you have a versatile combination for local data storage and management.