Skip to content

Connecting to SQLite Using Node.js

SQLite is a lightweight, serverless database engine that integrates easily with Node.js applications. On ruachost.com, you can connect to SQLite databases using the popular sqlite3 package.

  • Perfect for lightweight applications and prototyping.
  • Stores data in a single portable .db file.
  • Asynchronous I/O in Node.js makes queries fast and scalable.
  • No external database server required.
  1. Log in to your hosting account via SSH.

  2. Ensure Node.js is installed.

  3. Install the sqlite3 package:

    Terminal window
    npm install sqlite3
// Import sqlite3
import sqlite3 from 'sqlite3';
// Enable verbose mode for debugging
sqlite3.verbose();
// Connect to SQLite database file (creates if not exists)
const db = new sqlite3.Database('example.db');
// Run queries
db.serialize(() => {
db.run("CREATE TABLE employees (firstname TEXT, lastname TEXT, title TEXT)");
db.run("INSERT INTO employees VALUES ('Kelly', 'Koe', 'Engineer')");
db.each("SELECT firstname, lastname FROM employees", (err, row) => {
console.log(row.firstname + " " + row.lastname);
});
});
// Close connection
db.close();
  • If you see:

    SyntaxError: Cannot use import statement outside a module

    → Create a package.json file in your project directory and add:

    {
    "type": "module"
    }
  • This enables ES module syntax (import) in Node.js..