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.

 

Why Use Node.js with SQLite?

  • 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.

 

Steps to Connect to SQLite Using Node.js

Step 1: Install Node.js and sqlite3

  1. Log in to your hosting account via SSH.

  2. Ensure Node.js is installed.

  3. Install the sqlite3 package:

    Bash
    
    npm install sqlite3
    
 

Step 2: Write Connection Code

Example:

// 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();

Step 3: Handle Common Errors

  • 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..

 

Important Notes

  • Replace example.db with the path to your actual database file.

  • If the file does not exist, SQLite will create it automatically.

  • Always close the database connection (db.close()) to free resources.

  • Use prepared statements for secure queries against SQL injection.

 
Hjalp dette svar dig? 0 Kunder som kunne bruge dette svar (0 Stem)

Powered by WHMCompleteSolution