The Wayback Machine - https://web.archive.org/web/20231202060546/https://dev.to/codeboxx/javascript-sqlite-sql-database-in-browser-3962

DEV Community

Code Boxx
Code Boxx

Posted on

Javascript SQLite (SQL Database In Browser)

THE END OF WEBSQL

  • Once upon a time, there was WebSQL.
  • But WebSQL is deprecated and will be removed from browsers eventually.
  • Fear not, there is an alternative to create an SQLite database - Directly in the browser.

PART 1) SQLJS LIBRARY

PART 2) DATABASE INIT

var demo = {
  // (A) INITIALIZE
  db     : null,           // database object
  cache  : null,           // storage cache object
  cname  : "SQLDB",        // cache storage name
  dbname : "/demo.sqlite", // database storage name
  init : async () => {
    // (A1) STORAGE CACHE + SQLJS
    demo.cache = await caches.open(demo.cname);
    const SQL = await initSqlJs({
      locateFile: filename => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${filename}`
    });

    // (A2) ATTEMPT TO LOAD DATABASE FROM STORAGE CACHE
    demo.cache.match(demo.dbname).then(async r => {
      // (A2-1) NOT FOUND - CREATE A NEW DATABASE
      if (r==undefined) {
        demo.db = new SQL.Database();
        demo.db.run(`CREATE TABLE events (
          id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
          date TEXT NOT NULL,
          text TEXT NOT NULL
        )`);
        demo.db.run("CREATE INDEX date ON events (date)");
        await demo.export();
        await demo.run();
        demo.get();
      }

      // (A2-2) LOAD EXISTING DATABASE
      else {
        const buf = await r.arrayBuffer();
        demo.db = new SQL.Database(new Uint8Array(buf));
        demo.get();
      }
    });
  },

  // (B) EXPORT TO CACHE STORAGE
  export : async () => await demo.cache.put(
    demo.dbname, new Response(demo.db.export())
  ),
};

// (E) GO!
window.addEventListener("load", demo.init);
  • (A1 & A2-1) We only need SQL = await initSqlJs() and db = new SQL.Database() to create a new database. But the database only exists in the memory - Once the page reloads, everything is gone.
  • (B) To create a persistent database, we "export" the database to a cache storage.
  • (A1 & A2-2) On subsequent visits, we simply "restore" the database from the cache storage.

PART 3) INSERT UPDATE DELETE

var demo = {
  // (C) DEMO - INSERT/UPDATE EVENT
  run : async () => {
    // (C1) INSERT
    demo.db.run(
      `INSERT INTO events (date, text) VALUES (?,?), (?,?), (?,?)`, [
      "2077-06-05 00:00:00", "First event.",
      "2077-06-06 00:00:00", "Second event.",
      "2077-06-07 00:00:00", "Third event."
    ]);

    // (C2) UPDATE
    demo.db.run(
      `UPDATE events SET date=?, text=? WHERE id=?`,
      ["2077-06-06 00:00:00", "Second event EDITED.", 2]
    );

    // (C3) DELETE
    demo.db.run("DELETE FROM events WHERE id=?", [1]);

    // (C4) "COMMIT"
    await demo.export();
  },
};

Shouldn't be much trouble. We use db.run(QUERY, DATA) to run INSERT UPDATE REPLACE DELETE queries. Just remember to "commit" demo.export() the database to the storage cache at the end, or the changes will be lost.

PART 4) SELECT

var demo = {
  // (D) DEMO - GET EVENT
  get : () => {
    // (D1) GET SINGLE ENTRY
    let stmt = demo.db.prepare("SELECT * FROM events WHERE id=$id"),
    res = stmt.getAsObject({$id:2});
    console.log(res);

    // (D2) GET MULTIPLE ENTRIES
    stmt = demo.db.prepare(
      `SELECT * FROM events
      WHERE date BETWEEN $start AND $end`);
    stmt.bind({$start:"2077-06-01 00:00:00", $end:"2077-06-08 00:00:00"})
    while (stmt.step()) { 
      res = stmt.getAsObject();
      console.log(res);
    }
  }
};
  • To get a single row:
    • stmt = demo.db.prepare(SQL)
    • res = stmt.getAsObject({VAR:VALUE})
  • To get multiple rows:
    • stmt = demo.db.prepare(SQL)
    • stmt.bind({VAR:VALUE})
    • while (stmt.step()) { res = stmt.getAsObject(); }

THE END

That's all for this super condensed tutorial. Here are links to the GIST, the original blog post, and also a Calendar PWA where I put the "WASM SQLite" into good use.

Top comments (1)

 
krchetu profile image
Kushal •

Hi,

I need help where the sqllite file is stored in windows and how we can extract in android.