# @eggjs/rds 中文文档

规范地址：https://npmcn.com/package/%40eggjs/rds/

版本：1\.5\.0
npm 元数据更新时间：2026-06-30T15:34:35.609Z
中文译文更新时间：2026-11-13T09:24:12.082Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：103 kB，23 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 16\.17\.0
- 运行依赖：3 个
- 首次发布：2024-01-30T13:05:32.618Z
- 最新版本发布：2025-12-09T05:57:55.358Z
- 近 30 天下载量：6195（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 2 个）

## 中文简介

我的 RDS 客户端

## 安装

```sh
npm install @eggjs/rds
```

也可以使用：`pnpm add @eggjs/rds`、`yarn add @eggjs/rds`、`bun add @eggjs/rds`

## README

# @eggjs/rds (英语)

[![NPM version](https://img.shields.io/npm/v/@eggjs/rds.svg?style=flat-square)](https://npmjs.org/package/@eggjs/rds) [![Node.js CI](https://github.com/node-modules/rds/actions/workflows/nodejs.yml/badge.svg)](https://github.com/node-modules/rds/actions/workflows/nodejs.yml) [![Test coverage](https://codecov.io/github/node-modules/rds/coverage.svg?branch=master)](https://codecov.io/github/node-modules/rds?branch=master) [![npm download](https://img.shields.io/npm/dm/@eggjs/rds.svg?style=flat-square)](https://npmjs.org/package/@eggjs/rds)

一个RDS客户端. RDS,关系数据库服务. 与亚马逊相当 [RDS 软件](http://aws.amazon.com/rds/)。 。 。 .

支助 `MySQL` 只有协议.

## 使用量

### 创建 RDS 实例

```ts
import { RDSClient } from '@eggjs/rds';

const db = new RDSClient({
  host: 'your-rds-address.mysql.rds.aliyuncs.com',
  port: 3306,
  user: 'your-username',
  password: 'your-password',
  database: 'your-database-name',
  // optional params
  // The charset for the connection.
  // This is called "collation" in the SQL-level of MySQL (like utf8_general_ci).
  // If a SQL-level charset is specified (like utf8mb4)
  // then the default collation for that charset is used. (Default: 'UTF8_GENERAL_CI')
  // charset: 'utf8_general_ci',
  //
  // The maximum number of connections to create at once. (Default: 10)
  // connectionLimit: 10,
  //
  // The maximum number of connection requests the pool will queue
  // before returning an error from getConnection.
  // If set to 0, there is no limit to the number of queued connection requests. (Default: 0)
  // queueLimit: 0,
  // Set asyncLocalStorage manually for transaction
  // connectionStorage: new AsyncLocalStorage(),
  // If create multiple RDSClient instances with the same connectionStorage, use this key to distinguish between the instances
  // connectionStorageKey: 'datasource',
  
  // The timeout for connecting to the MySQL server. (Default: 500 milliseconds)
  // connectTimeout: 500,

  // The timeout for waiting for a connection from the connection pool. (Default: 500 milliseconds)
  // So max timeout for get a connection is (connectTimeout + poolWaitTimeout)
  // poolWaitTimeout: 500,
});
```

### 插入

-   插入一行

```js
const row = {
  name: 'fengmk2',
  otherField: 'other field value',
  createdAt: db.literals.now, // `now()` on db server
  // ...
};
const result = await db.insert('table-name', row);
console.log(result);
{ fieldCount: 0,
  affectedRows: 1,
  insertId: 3710,
  serverStatus: 2,
  warningCount: 2,
  message: '',
  protocol41: true,
  changedRows: 0 }
```

-   插入多行

将在交易和自动执行下执行.

```js
const rows = [
  {
    name: 'fengmk1',
    otherField: 'other field value',
    createdAt: db.literals.now, // `now()` on db server
    // ...
  },
  {
    name: 'fengmk2',
    otherField: 'other field value',
    createdAt: db.literals.now, // `now()` on db server
    // ...
  },
  // ...
];

const results = await db.insert('table-name', rows);
console.log(result);
{ fieldCount: 0,
  affectedRows: 2,
  insertId: 3840,
  serverStatus: 2,
  warningCount: 2,
  message: '&Records: 2  Duplicates: 0  Warnings: 0',
  protocol41: true,
  changedRows: 0 }
```

### 更新

-   用主密钥更新一行 : `id`

```js
const row = {
  id: 123,
  name: 'fengmk2',
  otherField: 'other field value',
  modifiedAt: db.literals.now, // `now()` on db server
};
const result = await db.update('table-name', row);
console.log(result);
{ fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '(Rows matched: 1  Changed: 1  Warnings: 0',
  protocol41: true,
  changedRows: 1 }
```

-   更新行 `options.where` 财务报告和审定财务报表 `options.columns`

```js
const row = {
  name: 'fengmk2',
  otherField: 'other field value',
  modifiedAt: db.literals.now, // `now()` on db server
};
const result = await db.update('table-name', row, {
  where: { name: row.name },
  columns: [ 'otherField', 'modifiedAt' ]
});
console.log(result);
{ fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '(Rows matched: 1  Changed: 1  Warnings: 0',
  protocol41: true,
  changedRows: 1 }
```

### 更新多行

-   用主密钥更新多行 : `id`

```js
const options = [{
  id: 123,
  name: 'fengmk2',
  email: 'm@fengmk2.com',
  otherField: 'other field value',
  modifiedAt: db.literals.now, // `now()` on db server
}, {
   id: 124,
  name: 'fengmk2_2',
  email: 'm@fengmk2_2.com',
  otherField: 'other field value 2',
  modifiedAt: db.literals.now, // `now()` on db server
}]
const result = await db.updateRows('table-name', options);
console.log(result);
{ fieldCount: 0,
  affectedRows: 2,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '(Rows matched: 2  Changed: 2  Warnings: 0',
  protocol41: true,
  changedRows: 2 }
```

-   更新多行 `row` 财务报告和审定财务报表 `where` 属性

```js
const options = [{
  row: {
    email: 'm@fengmk2.com',
    otherField: 'other field value',
    modifiedAt: db.literals.now, // `now()` on db server
  },
  where: {
    id: 123,
    name: 'fengmk2',
  }
}, {
  row: {
    email: 'm@fengmk2_2.com',
    otherField: 'other field value2',
    modifiedAt: db.literals.now, // `now()` on db server
  }, 
  where: {
    id: 124,
    name: 'fengmk2_2',
  }
}]
const result = await db.updateRows('table-name', options);
console.log(result);
{ fieldCount: 0,
  affectedRows: 2,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '(Rows matched: 2  Changed: 2  Warnings: 0',
  protocol41: true,
  changedRows: 2 }
```

### 获取

-   排队

```js
const row = await db.get('table-name', { name: 'fengmk2' });

=> SELECT * FROM `table-name` WHERE `name` = 'fengmk2'
```

### 选择

-   选择所有行

```js
const rows = await db.select('table-name');

=> SELECT * FROM `table-name`
```

-   选择带有条件的行

```js
const rows = await db.select('table-name', {
  where: {
    type: 'javascript'
  },
  columns: ['author', 'title'],
  orders: [['id', 'desc']]
});

=> SELECT `author`, `title` FROM `table-name`
 WHERE `type` = 'javascript' ORDER BY `id` DESC
```

### 删除

-   以条件删除

```js
const result = await db.delete('table-name', {
  name: 'fengmk2'
});

=> DELETE FROM `table-name` WHERE `name` = 'fengmk2'
```

### 计数

-   从表格中计数到条件

```js
const count = await db.count('table-name', {
  type: 'javascript'
});

=> SELECT COUNT(*) AS count FROM `table-name` WHERE `type` = 'javascript';
```

### 交易

开始交易、 承诺或回滚

```js
const tran = await db.beginTransaction();

try {
  await tran.insert(table, row1);
  await tran.update(table, row2);
  await tran.commit();
} catch (err) {
  // error, rollback
  await tran.rollback(); // rollback call won't throw err
  throw err;
}
```

#### 范围交易

API : (英语) `async beginTransactionScope(scope)`

在范围中运行的所有查询都将在同一交易下进行. 我们会自动为您承诺或退后.

```js
const result = await db.beginTransactionScope(async conn => {
  // don't commit or rollback by yourself
  await conn.insert(table, row1);
  await conn.update(table, row2);
  return { success: true };
});
// if error throw on scope, will auto rollback
```

单位 `Promise.all` 实例中,并行开始交易程序将创建孤立的交易.

```js
const result = await Promise.all([
  db.beginTransactionScope(async conn => {
    // commit and success
  }),
  db.beginTransactionScope(async conn => {
    // throw err and rollback
  }),
])
```

### 原始查询

-   无参数查询

```js
const rows = await db.query('SELECT * FROM your_table LIMIT 100');
console.log(rows);
```

-   查询数组参数

```js
const rows = await db.query('SELECT * FROM your_table WHERE id=?', [ 123 ]);
console.log(rows);
```

-   用对象参数查询

```js
const rows = await db.query('SELECT * FROM your_table WHERE id=:id', { id: 123 });
console.log(rows);
```

### 自定义查询生命圈

```ts
db.beforeQuery((sql: string) => {
  // change sql string
  return `/* add custom format here */ ${sql}`;
});

db.afterQuery((sql: string, result: any, execDuration: number, err?: Error) => {
  // handle logger here
});
```

## APIs 密码

-   `*` 表示此函数可以生成 .

### IO 查询

-   aync 查询( sql\[, 值)
-   aync 查询 One( sql) \[, 值\]
-   aync 选择(表,选项)
-   async 获取(表格,在哪里,选项)
-   aync 插入(表,行,选项)
-   aync 更新(表、行、选项)
-   aync 更新 Rows(表,选项)
-   自动删除( 表格, 其中)
-   async 计数(表,在哪里)

### 交易助手

-   async 开始交易( )
-   aync 开始交易范围( 镜片)

### 用户

-   出局( 值, 字符串对象, 时间区)
-   caveId( 值, 禁止合格)
-   格式( sql, 值, 字符串对象, 时区)

### 文学

```js
await db.insert('user', {
  name: 'fengmk2',
  createdAt: db.literals.now,
});

=>

INSERT INTO `user` SET `name` = 'fengmk2', `createdAt` = now()
```

#### 自定义字元

```js
const session = new db.literals.Literal('session()');
```

## 类别关系

```txt
+-----------+                          +----------------+
| RDSClient +-- beginTransaction() --> + RDSTransaction |
+--+----+---+                          +----+----+------+
   |    | getConnection()            .conn  |    |
   |    |         +---------------+         |    |
   |    +-------->+ RDSConnection +<--------+    |
   |              +-------+-------+              |
   |                      | extends              |
   |                      v                      |
   |   extends    +-------+-------+    extends   |
   +------------->+   Operator    +<-------------+
                  |    query()    |
                  +---------------+
```

## 给当地的 def

运行套接字来开始测试 Mysql 服务

```bash
docker compose -f docker-compose.yml up -d
# if you run the first time, should wait for ~20s to let mysql service init started
```

运行单元测试

```bash
npm test
```

停止测试 Mysql 服务

```bash
docker compose -f docker-compose.yml down
```

## 许可证

[麻省理工学院](https://npmcn.com/package/%40eggjs/rds/LICENSE)

## 贡献者

[![Contributors](https://contrib.rocks/image?repo=node-modules/rds)](https://github.com/node-modules/rds/graphs/contributors)

制造的 [贡献者-img](https://contrib.rocks/)。 。 。 .

## 常见问题

### @eggjs/rds 是什么？

我的 RDS 客户端

### 如何安装 @eggjs/rds？

在项目目录运行 npm install @eggjs/rds，或使用 pnpm add / yarn add / bun add。

### @eggjs/rds 支持 TypeScript 吗？

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

### @eggjs/rds 支持 ESM 还是 CommonJS？

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

### @eggjs/rds 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 16\.17\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @eggjs/rds 可以商用吗？

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

### @eggjs/rds 的下载量有多少？

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

### @eggjs/rds 还在维护吗？

最新版本 1\.5\.0 发布于 2025/12/09（11 个月前）；至今共发布 9 个版本，其中过去 12 个月发布了 2 个；首次发布于 2024/01/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

