# @foxglove/sql\.js 中文文档

规范地址：https://npmcn.com/package/%40foxglove/sql.js/

版本：0\.0\.4
npm 元数据更新时间：2025-08-20T03:32:13.083Z
中文译文更新时间：2026-11-15T10:41:42.422Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40foxglove/sql.js
原文对照：https://npmcn.com/package/%40foxglove/sql.js/?lang=original
项目主页：http://github.com/sql-js/sql.js
源码仓库：https://github.com/sql-js/sql.js

弃用说明：This package is no longer maintained

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：28.5 MB，24 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2021-12-14T18:00:16.225Z
- 最新版本发布：2021-12-31T01:29:41.660Z
- 近 30 天下载量：61639（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：4（近 12 个月 0 个）

## 中文简介

支持开放和编写数据库的SQLite图书馆,编写报表,等等。 此 SQLite 文库为纯javascript (由标注而成).

## 安装

```sh
npm install @foxglove/sql.js
```

也可以使用：`pnpm add @foxglove/sql.js`、`yarn add @foxglove/sql.js`、`bun add @foxglove/sql.js`

## README

![](https://user-images.githubusercontent.com/552629/76405509-87025300-6388-11ea-86c9-af882abb00bd.png)

# SQLite 编译为 JavaScript

[![CI status](https://github.com/sql-js/sql.js/workflows/CI/badge.svg)](https://github.com/sql-js/sql.js/actions) [![npm](https://img.shields.io/npm/v/sql.js)](https://www.npmjs.com/package/sql.js) [![CDNJS version](https://img.shields.io/cdnjs/v/sql.js.svg)](https://cdnjs.com/libraries/sql.js)

_sql.js (英语)_ 是一个 Javascript SQL 数据库。 它允许您创建关系数据库,并完全在浏览器中查询. 你可以试试看 [此在线演示](https://sql.js.org/examples/GUI/)它使用 [存储在内存中的虚拟数据库文件](https://emscripten.org/docs/porting/files/file_systems_overview.html),因此 **不坚持的改变** 输入数据库 然而,它允许你 **导入** 任何已存在的 sqlite 文件,并改为 **导出** 作为创建的数据库 [JavaScript 键入数组](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)。 。 。 .

_sql.js (英语)_ 用途 [标记](https://emscripten.org/docs/introducing_emscripten/about_emscripten.html) 要编译 [SQL 点](http://sqlite.org/about.html) 至web组装(或与旧浏览器兼容的javascript代码)。 它包括 [贡献的数学和字符串扩展函数](https://www.sqlite.org/contrib?orderby=date)。 。 。 .

sql.js可以像任何传统的JavaScript库一样被使用. 如果您正在 JavaScript( 例如使用 Electron) 构建本地应用程序, 或者在节点工作, 您可能更喜欢使用 [本地绑定 SQLite 到 JavaScript](https://www.npmjs.com/package/sqlite3). 原生装订不仅会因为会运行原生代码而更快,而且还能直接在数据库文件上工作,而不必将整个数据库装入内存,避免内存出错并进一步改善性能.

SQLite为公有领域, sql.js为麻省理工学院许可.

## API 文档

A 类 [aPI 完整文档](https://sql.js.org/documentation/) 所有现有课程和方法都有. 是源代码内部的评论产生的,因此总是最新的.

## 使用量

默认, _sql.js (英语)_ 用途 [原声](https://developer.mozilla.org/en-US/docs/WebAssembly),因此需要装入 `.wasm` 除javascript 库外还有文件。 您可以在 `./node_modules/sql.js/dist/sql-wasm.wasm` 从 npm 安装 sql.js 后,并指示您的捆绑者将其添加到您的静态资产中或从中加载 [a CDN (中文(简体) )](https://cdnjs.com/libraries/sql.js)。然后使用 [`locateFile`](https://emscripten.org/docs/api_reference/module.html#Module.locateFile) 配置对象的属性 `initSqlJs` 以显示文件的位置。 如果您使用 Webpack 等资产构建器,您可以自动化此功能. 见 [此演示如何将 sql](https://github.com/sql-js/react-sqljs-demo)。 。 。 .

```javascript
const initSqlJs = require('sql.js');
// or if you are in a browser:
// const initSqlJs = window.initSqlJs;

const SQL = await initSqlJs({
  // Required to load the wasm binary asynchronously. Of course, you can host it wherever you want
  // You can omit locateFile completely when running in node
  locateFile: file => `https://sql.js.org/dist/${file}`
});

// Create a database
const db = new SQL.Database();
// NOTE: You can also use new SQL.Database(data) where
// data is an Uint8Array representing an SQLite database file


// Execute a single SQL string that contains multiple statements
let sqlstr = "CREATE TABLE hello (a int, b char); \
INSERT INTO hello VALUES (0, 'hello'); \
INSERT INTO hello VALUES (1, 'world');";
db.run(sqlstr); // Run the query without returning anything

// Prepare an sql statement
const stmt = db.prepare("SELECT * FROM hello WHERE a=:aval AND b=:bval");

// Bind values to the parameters and fetch the results of the query
const result = stmt.getAsObject({':aval' : 1, ':bval' : 'world'});
console.log(result); // Will print {a:1, b:'world'}

// Bind other values
stmt.bind([0, 'hello']);
while (stmt.step()) console.log(stmt.get()); // Will print [0, 'hello']
// free the memory used by the statement
stmt.free();
// You can not use your statement anymore once it has been freed.
// But not freeing your statements causes memory leaks. You don't want that.

const res = db.exec("SELECT * FROM hello");
/*
[
  {columns:['a','b'], values:[[0,'hello'],[1,'world']]}
]
*/

// You can also use JavaScript functions inside your SQL code
// Create the js function you need
function add(a, b) {return a+b;}
// Specifies the SQL function's name, the number of it's arguments, and the js function to use
db.create_function("add_js", add);
// Run a query in which the function is used
db.run("INSERT INTO hello VALUES (add_js(7, 3), add_js('Hello ', 'world'));"); // Inserts 10 and 'Hello world'

// Export the database to an Uint8Array containing the SQLite database file
const binaryArray = db.export();
```

## 演示

有几个例子 [此处可用](https://sql-js.github.io/sql.js/index.html)。最全面性是 [Sqlite 口译员](https://sql-js.github.io/sql.js/examples/GUI/index.html)。 。 。 .

## 实例

测试文件提供了使用 api 的最新实例 .

### 浏览器内部

#### 示例 **HTML 语言** 文件 :

```html
<meta charset="utf8" />
<html>
  <script src='/dist/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>
```

#### 从用户选择的文件创建数据库

`SQL.Database` 构造器将代表数据库文件的整数组作为可选参数. 以下代码使用 HTML 输入作为输入数据库的来源 :

```javascript
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);
}
```

见: [https://sql-js.github.io/sql.js/examples/GUI/gui.js 互联网档案馆的存檔,存档日期2013-12-12](https://sql-js.github.io/sql.js/examples/GUI/gui.js)

#### 从服务器上装入数据库

##### 使用获取

```javascript
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));
```

##### 使用 XMLHttp 请求

```javascript
const xhr = new XMLHttpRequest();
// For example: https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite
xhr.open('GET', '/path/to/database.sqlite', true);
xhr.responseType = 'arraybuffer';

xhr.onload = e => {
  const uInt8Array = new Uint8Array(xhr.response);
  const db = new SQL.Database(uInt8Array);
  const contents = db.exec("SELECT * FROM my_table");
  // contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
};
xhr.send();
```

见: [https://github.com/sql-js/sql.js/wiki/Load-a-database- from-the-server 互联网档案馆的存檔,存档日期2013-12-22](https://github.com/sql-js/sql.js/wiki/Load-a-database-from-the-server)

### 从节点.js 使用

`sql.js` 实值 [npm 时主机](https://www.npmjs.org/package/sql.js)。要安装它,你可以简单地运行 `npm install sql.js`。 。 。 . 或者,你可以简单地下载 `sql-wasm.js` 财务报告和审定财务报表 `sql-wasm.wasm`,从下面的下载链接.

#### 从磁盘上读取数据库 :

```javascript
const fs = require('fs');
const initSqlJs = require('sql-wasm.js');
const filebuffer = fs.readFileSync('test.sqlite');

initSqlJs().then(function(SQL){
  // Load the db
  const db = new SQL.Database(filebuffer);
});

```

#### 将数据库写入磁盘

您需要转换结果 `db.export` 到缓冲器

```javascript
const fs = require("fs");
// [...] (create the database)
const data = db.export();
const buffer = new Buffer(data);
fs.writeFileSync("filename.sqlite", buffer);
```

见: [https://github.com/sql-js/sql.js/blob/master/test/test node file.js (中文(简体) )](https://github.com/sql-js/sql.js/blob/master/test/test_node_file.js)

### 用作网络工人

如果您不想在主应用程序线索中运行 CPU 密集 SQL 查询, 您可以使用 _比较有限_ 网工API.

您需要下载 `worker.sql-wasm.js` 财务报告和审定财务报表 `worker.sql-wasm.wasm` 从 [页面](https://github.com/sql-js/sql.js/releases)。 。 。 .

示例

```html
<script>
  const worker = new Worker("/dist/worker.sql-wasm.js");
  worker.onmessage = () => {
    console.log("Database opened");
    worker.onmessage = event => {
      console.log(event.data); // The result of the query
    };

    worker.postMessage({
      id: 2,
      action: "exec",
      sql: "SELECT age,name FROM test WHERE id=$id",
      params: { "$id": 1 }
    });
  };

  worker.onerror = e => console.log("Worker error: ", e);
  worker.postMessage({
    id:1,
    action:"open",
    buffer:buf, /*Optional. An ArrayBuffer representing an SQLite Database file*/
  });
</script>
```

### 启用 BigInt 支持

如果你需要的话 `BigInt` 支持,它得到部分支持,因为大多数浏览器现在都支持它包括了Safari. 装订 `BigInt` 仍然不支持,仅获取 `BigInt` 从数据库中获取支持.

```html
<script>
  const stmt = db.prepare("SELECT * FROM test");
  const config = {useBigInt: true};
  /*Pass optional config param to the get function*/
  while (stmt.step()) console.log(stmt.get(null, config));

  /*OR*/
  const result = db.exec("SELECT * FROM test", config);
  console.log(results[0].values)
</script>
```

在WebWorker上,你可以只添加 `config` 发布消息前的参数 。 有了这个,你不必通过配置参数 `get` 函数.

```html
<script>
  worker.postMessage({
    id:1,
    action:"exec",
    sql: "SELECT * FROM test",
    config: {useBigInt: true}, /*Optional param*/
  });
</script>
```

见 [实例/GUI/gui.js](https://npmcn.com/package/%40foxglove/sql.js/examples/GUI/gui.js) 对于一个完整的例子.

## 目标/下载数

这个图书馆包括了Sqlite的WebAssembly和asm.js版本. (WebAssembly是更新的,首选的编译方式为JavaScript,并已经超越了asm.js. 它产生较小,更快的代码. ) 包含Asm.js版本的相容性.

## 从0.x升级到1.x

Sql.js的1.0版本必须同步装入,而asm.js则能够同步装入.

所以在过去 你会:

```html
<script src='js/sql.js'></script>
<script>
  const db = new SQL.Database();
  //...
</script>
```

或:

```javascript
const SQL = require('sql.js');
const db = new SQL.Database();
//...
```

1.x版本:

```html
<script src='dist/sql-wasm.js'></script>
<script>
  initSqlJs({ locateFile: filename => `/dist/${filename}` }).then(function(SQL){
    const db = new SQL.Database();
    //...
  });
</script>
```

或:

```javascript
const initSqlJs = require('sql-wasm.js');
initSqlJs().then(function(SQL){
  const db = new SQL.Database();
  //...
});
```

`NOTHING` 现在在SQLite中是一个保留词,而以前它不是。 这可能造成错误,如 `Error: near "nothing": syntax error`

### 下载/使用:

虽然asm.js文件作为单一Javascript文件分发,但WebAssembly作为一对文件分发效率最高 `.js` 加载器和 `.wasm` 文档,比如 `sql-wasm.js` 财务报告和审定财务报表 `sql-wasm.wasm`编辑 `.js` 文件负责装入 `.wasm` 文档。 你可以从我们身上找到这些文件 [页面](https://github.com/sql-js/sql.js/releases)

## 分布式文物中的 sql.js版本

你总能找到最新出版的文物 [https://github.com/sql-js/sql.js/releases/latest (中文(简体) )](https://github.com/sql-js/sql.js/releases/latest)。 。 。 .

每笔 [释放](https://github.com/sql-js/sql.js/releases/),你会找到一个名为 `sqljs.zip` 输入 _释放资产_它将包括:

-   `sql-wasm.js` : Sql.js的Web大会版. 已消化并适合生产。 用这个 如果您使用此选项, 您需要包含/ ship `sql-wasm.wasm` 还有.
-   `sql-wasm-debug.js` : Web Assembly, Sql.js 调试版本. 更大的, 与断言打开。 有利于地方发展. 您需要包含/舰艇 `sql-wasm-debug.wasm` 如果你用这个.
-   `sql-asm.js` : Sql.js更古老的Asm.js版本. 较慢而更大. 出于兼容性原因提供.
-   `sql-asm-memory-growth.js` : Asm.js不允许内存在默认情况下增长,因为其速度较慢并非优化. 如果您正在使用 sql-asm.js 并看到这个错误(`Cannot enlarge memory arrays`,使用此文件.
-   `sql-asm-debug.js` 编号: _调试_ asm.js版本的Sql.j. 利用这个进行地方发展.
-   `worker.*` - 上述图书馆的网络工作者版本。 比较有限度的API. 见 [实例/GUI/gui.js](https://npmcn.com/package/%40foxglove/sql.js/examples/GUI/gui.js) 对于一个很好的例子.

## 汇编/撰稿

这个图书馆的一般消费者不需要再读了. (汇编的文件可通过 [页面](https://github.com/sql-js/sql.js/releases). ) (中文(简体) )

如果您想为 Web Assembly 编译自己的 SQLite 版本, 或者想要为此工程贡献, 请参见 [捐款额](https://npmcn.com/package/%40foxglove/sql.js/CONTRIBUTING.md)。 。 。 .

## 常见问题

### @foxglove/sql\.js 是什么？

支持开放和编写数据库的SQLite图书馆,编写报表,等等。 此 SQLite 文库为纯javascript \(由标注而成\)\.注意：该包已被作者标记为弃用——This package is no longer maintained

### 如何安装 @foxglove/sql\.js？

在项目目录运行 npm install @foxglove/sql\.js，或使用 pnpm add / yarn add / bun add。

### @foxglove/sql\.js 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @foxglove/sql\.js 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @foxglove/sql\.js 可以商用吗？

@foxglove/sql\.js 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @foxglove/sql\.js 的下载量有多少？

根据 npm 官方下载统计，@foxglove/sql\.js 在 2026/10/16 – 2026/11/14 这 30 天内被下载 61,639 次，日均约 2,055 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @foxglove/sql\.js 还在维护吗？

最新版本 0\.0\.4 发布于 2021/12/31（4 年前）；至今共发布 4 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/12/15。作者已将其标记为弃用，新项目建议寻找替代方案。

