可运行在浏览器中的Sqlite

1,678 阅读1分钟

Sql.js 官网

安装运行

cdn方式 cdn : cdnjs.com/libraries/s…
cdn(js) : cdnjs.cloudflare.com/ajax/libs/s…
cdn(wasm) : cdnjs.cloudflare.com/ajax/libs/s…

npm方式 npm i sql.js -S npm i @types/sql.js -S

<meta charset="utf8" />
<html>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.7.0/sql-wasm.js'></script>
  <script>
    config = {
      locateFile: filename => `/dist/${filename}`
    }
    // The `initSqlJs` function is globally provided by all of the main dist files if loaded in the browser.
    // We must specify this locateFile function if we are loading a wasm file from anywhere other than the current html page's folder.
    initSqlJs(config).then(function(SQL){
      //Create the database
      const 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));
      }
    });
  </script>
  <body>
    Output is in Javascript console
  </body>
</html>

与webpack一起用法

默认情况下,sql.js使用wasm,因此.wasm除了 javascript 库之外还需要加载一个文件。您可以在./node_modules/sql.js/dist/sql-wasm.wasm从 npm 安装 sql.js 后找到此文件,并指示您的捆绑器将其添加到您的静态资产或从CDN加载它。然后使用locateFile传递的配置对象的属性initSqlJs来指示文件的位置。如果您使用诸如 webpack 之类的资产构建器,您可以自动执行此操作。请参阅如何将 sql.js 与 webpack 集成(和反应)的演示

API文档

sql.js.org/documentati…

官方例子

image.png