TechTorch

Location:HOME > Technology > content

Technology

How to Integrate SQLite with JavaScript: Server and Client-Side

February 06, 2025Technology4114
How to Integrate SQLite with JavaScript: Server and Client-Side SQLite

How to Integrate SQLite with JavaScript: Server and Client-Side

SQLite is a widely-used, lightweight, and powerful database library. This article will guide you through integrating SQLite with JavaScript in both Node.js and the browser. We'll explore the necessary libraries and provide example code snippets for each environment.

Using SQLite in Node.js

For server-side applications, you can utilize the Node.js package sqlite3, which is a popular library for interacting with SQLite databases. Here's a detailed step-by-step process, along with a code example, to help you integrate SQLite in a Node.js project.

Installation

Ensure you have Node.js installed. Create a new project and navigate to it. Install the sqlite3 package using npm.
mkdir my-projectcd my-projectnpm init -ynpm install sqlite3

Basic Usage

Below is a simple example of how to use SQLite in a Node.js environment:

const sqlite3  require('sqlite3').verbose();// Connect to a database or create it if it doesn't existlet db  new ('my-database.db', err  {    if (err) {        ('Unable to connect to the SQLite database: '   );        return;    }    console.log('Connected to the SQLite database.');});// Create a tableconst createTableQuery  `CREATE TABLE IF NOT EXISTS users (    id INTEGER PRIMARY KEY AUTOINCREMENT,    name TEXT,    email TEXT)`;const runCreateTable  ()  {    (createTableQuery, (err)  {        if (err) {            ('Error creating table: '   );            return;        }        console.log('Table created successfully');    });};runCreateTable();// Insert dataconst insertData  `INSERT INTO users (name, email) VALUES (?, ?)`;const runInsertData  ()  {    const stmt  (insertData);    ('John Doe', 'john@', (err)  {        if (err) {            ('Error inserting data: '   );            return;        }        console.log('Data inserted successfully');    });    ();};runInsertData();// Query dataconst queryData  `SELECT * FROM users`;const runQuery  ()  {    db.each(queryData, (err, row)  {        if (err) {            ('Error querying data: '   );            return;        }        console.log(row);    });};runQuery();// Close the database connection(err  {    if (err) {        ('Error closing the database: '   );        return;    }    console.log('Closed the database connection.');});

Using SQLite in the Browser

For client-side applications, you can use the sql.js library, which allows you to run SQLite in the browser using WebAssembly. Here's how to integrate it in a simple HTML file.

Installation

You can include the sql.js library via a CDN or install it via npm. For simplicity, we'll include it using a CDN in this example.

    SQLite in Browser        initSqlJs().then(SQL  {            // Create a database            const db  new ();            // Create a table            const createTableQuery  `            CREATE TABLE IF NOT EXISTS users (                id INTEGER PRIMARY KEY AUTOINCREMENT,                name TEXT,                email TEXT            )            `;            const runCreateTable  ()  {                (createTableQuery, (err)  {                    if (err) {                        ('Error creating table: '   );                        return;                    }                    console.log('Table created successfully');                });            };            runCreateTable();            // Insert data            const insertData  `            INSERT INTO users (name, email) VALUES (?, ?)            `;            const runInsertData  ()  {                const stmt  (insertData);                ('John Doe', 'john@', (err)  {                    if (err) {                        ('Error inserting data: '   );                        return;                    }                    console.log('Data inserted successfully');                });                ();            };            runInsertData();            // Query data            const queryData  `            SELECT * FROM users            `;            const runQuery  ()  {                const result  db.exec(queryData);                console.log(result);            };            runQuery();            // Free the database            ();        });

Summary

Node.js:

Use the sqlite3 package to interact with SQLite databases.

Browsers:

Use sql.js to run SQLite in the browser using WebAssembly.

These examples should help you get started with SQLite in both environments! Let me know if you have any questions or need further assistance.

Keywords: SQLite, JavaScript, Node.js, sql.js, WebAssembly