Skip to content
Andrew Chan edited this page Jun 6, 2023 · 6 revisions

介紹

SQLite是一個開源(MIT Licensed)的關係數據庫(Relational Database)
SQLite使用emscripten編譯成Wasm (WebAssembly),可以經由SQL.js引入SQLite使用
數據庫由於使用瀏覽器的內存,所有對數據庫作出的改動若沒有導出將會失去
導出的數據庫文件應為.sqlite檔案,當然SQLite可以導入.sqlite檔案,這個.sqlite檔案應該是一個JavaScript typed array
sql.js可以作為傳統的JS Library使用,如果你正在建設原生(Native)/node.js的網站,你可以使用Native Binding去載入sql.js

例子參考

如想知道更多可看例子參考,以了解如何在HTML中使用SQLite
sql.js已供在cdnjs上存取,你可以加上<script>來引用相關的JS

<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>

更多例子和相關文檔可於SQLite官方網頁查看

創建新數據庫

initSqlJs(config).then(function(SQL){
      //Create the database
      db = new SQL.Database();
      // Run a query without reading the results
      db.run("CREATE TABLE test (col1, col2);");
      // Insert two rows: (1,111) and (2,222)
      db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);

      // Prepare a statement
      const stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
      stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}

      // Bind new values
      stmt.bind({$start:1, $end:2});
      while(stmt.step()) { //
        const row = stmt.getAsObject();
        console.log('Here is a row: ' + JSON.stringify(row));
      }
    });

導出數據庫

Method 1:

dbFileElm.onchange = () => {
  const f = dbFileElm.files[0];
  const r = new FileReader();
  r.onload = function() {
    const Uints = new Uint8Array(r.result);
    db = new SQL.Database(Uints);
  }
  r.readAsArrayBuffer(f);
}

Method 2:

async function saveDatabase() {
  // const db = new SQL.Database();
  // [...](create the database)
  const data = db.export();
  const blob = new Blob([data], { type: 'application/octet-stream' });
  saveAs(blob, 'filename.sqlite');
  console.log('Database saved successfully.');
}

導入數據庫

Method 1:

const sqlPromise = initSqlJs({
  locateFile: file => `https://path/to/your/dist/folder/dist/${file}`
});
const dataPromise = fetch("/path/to/database.sqlite").then(res => res.arrayBuffer());
const [SQL, buf] = await Promise.all([sqlPromise, dataPromise])
const db = new SQL.Database(new Uint8Array(buf));

Method 2:

async function loadDatabase() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.sqlite';
  input.onchange = async function(e) {
    const file = input.files[0];
    const filebuffer = await file.arrayBuffer();
    db = new gSql.Database(new Uint8Array(filebuffer));
    console.log('Database loaded successfully.');
  };
  input.click();
}

Stored Procedure

數據庫瀏覽器 (DB4S)

DB Browser for SQLite (DB4S)提供一個高質量可視化的開源工具以便用戶新增、修改及設計SQLite數據庫檔案
同時支援Windows, macOS和Linux

參考文件

Application Reference
SQLite SQL.js:在浏览器中创建和查询一个关系数据库
SQLite sqlite3 WebAssembly & JavaScript Documentation Index
SQLite SQLite Stored Procedures
SQLite & GitHub Hosting SQLite databases on Github Pages
DB4S DB Browser for SQLite