# @fastify/mysql 中文文档

规范地址：https://npmcn.com/package/%40fastify/mysql/

版本：5\.0\.5
npm 元数据更新时间：2026-10-18T12:30:53.404Z
中文译文更新时间：2026-11-14T11:25:13.142Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：53.6 kB，17 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2022-04-27T14:01:14.319Z
- 最新版本发布：2026-10-15T09:34:03.200Z
- 近 30 天下载量：35531（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：13（近 12 个月 3 个）

## 中文简介

快速化 Mysql 连接插件

## 安装

```sh
npm install @fastify/mysql
```

也可以使用：`pnpm add @fastify/mysql`、`yarn add @fastify/mysql`、`bun add @fastify/mysql`

## README

# @ fastify/ misql (中文(简体) )

[![CI](https://github.com/fastify/fastify-mysql/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-mysql/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/mysql.svg?style=flat)](https://www.npmjs.com/package/@fastify/mysql) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

快速化 MySQL 连接插件; 您可以通过此程序在服务器的每个部分共享相同的 MySQL 连接池 . 盖下 [mysql2 (英语)](https://github.com/sidorares/node-mysql2) 已使用。 如果你没有使用 `connectionString` 选项 `register` 将传递给 MySQL 游泳池建造者.

_重要内容:_ 所有 MySQL2 选项在使用时将被忽略 `connectionString`,如果想要将额外选项传递给 MySQL2 使用 `uri` 改为 `connectionString`。 。 。 .

## 安装

```
npm i @fastify/mysql
```

### 兼容性

| 插件版本 | 快速化版本 |
| --- | --- |
| `>=5.x` | `^5.x` |
| `^4.x` | `^4.x` |
| `>=2.x <4.x` | `^3.x` |
| `>=0.x <2.x` | `^2.x` |
| `>=0.x <2.x` | `^1.x` |

请注意,如果一个快取版本没有支持,那么该插件的相应版本也一样 上表列出. 见 [快速化 LTS 政策](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) 更多细节.

## 使用量

添加到您的项目 `register` 你们就完了! 此插件将添加 `mysql` 在您快速化实例中的命名空间,其属性如下:

```
pool: the pool instance
query: an utility to perform a query without a transaction
execute: an utility to perform a prepared statement without a transaction
getConnection: get a connection from the pool
format: an utility to generate SQL string
escape: an utility to escape query values
escapeId: an utility to escape query identifiers
```

示例

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/mysql'), {
  connectionString: 'mysql://root@localhost/mysql'
})

fastify.get('/user/:id', (req, reply) => {
  fastify.mysql.getConnection(onConnect)

  function onConnect (err, client) {
    if (err) return reply.send(err)

    client.query(
      'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],
      function onResult (err, result) {
        client.release()
        reply.send(err || result)
      }
    )
  }
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

使用 `mysql.query`

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/mysql'), {
  connectionString: 'mysql://root@localhost/mysql'
})

fastify.get('/user/:id', (req, reply) => {
  fastify.mysql.query(
    'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],
    function onResult (err, result) {
      reply.send(err || result)
    }
  )
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

你可以看到,没有必要关闭客户端,因为它是内部完成的.

### 集合选项

默认情况下,此插件将创建一个 [`mysql2` 组合](https://sidorares.github.io/node-mysql2/docs#using-connection-pools)。如果你不通过 `connectionString`,在插件中注册的每个 MySQL 选项都会转发到 `mysql2.createPool()`数字 :

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/mysql'), {
  host: 'localhost',
  user: 'root',
  database: 'mysql',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
})

fastify.get('/users', (req, reply) => {
  fastify.mysql.query(
    'SELECT id, username FROM users',
    function onResult (err, result) {
      reply.send(err || result)
    }
  )
})
```

> **重要**编号 : `mysql2` 使用时忽略集合选项 `connectionString`。如果需要附加选项和连接字符串,请使用 `uri` 改为 `connectionString`。 。 。 .

也可以使用相同的集合选项 `promise: true`;如果是这样的话,池是用 `mysql2/promise`数字 :

```js
fastify.register(require('@fastify/mysql'), {
  promise: true,
  host: 'localhost',
  user: 'root',
  database: 'mysql',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
})
```

在注册时支持 Async/await `promise` 选项 `true`数字 :

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/mysql'), {
  promise: true,
  connectionString: 'mysql://root@localhost/mysql'
})

fastify.get('/user/:id', async (req, reply) => {
  const connection = await fastify.mysql.getConnection()
  const [rows, fields] = await connection.query(
    'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],
  )
  connection.release()
  return rows[0]
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

### 命名实例范围

被命名的客户端由后人Fastify范围继承. 在孩子身上添加名字 范围创建包含继承客户端的本地注册;不添加 给父母或兄弟姐妹的名字。 独立的兄弟姐妹可以重用一个名字,但是 无法替换继承的名字 .

未名客户端可以先注册,再注册名客户端. 名称不得 与现有的客户端属性相撞, 例如 `query`, (中文(简体) ), `pool`,或 `format`。 。 。 . `__proto__`, (中文(简体) ), `constructor`,以及 `toString` 支持和检查重复, 包括未命名的登记之后.

## 类型脚本

作为 `mysql2` 显示四种不同类型的客户端, 我们没有指定您的打字方式 。 您需要按照下面的例子指定类型 .

```ts
import { MySQLConnection, MySQLPool, MySQLPromiseConnection, MySQLPromisePool } from '@fastify/mysql'

// if you only pass connectionString
declare module 'fastify' {
  interface FastifyInstance {
    mysql: MySQLPool
  }
}

// if you passed type = 'connection'
declare module 'fastify' {
  interface FastifyInstance {
    mysql: MySQLConnection
  }
}

// if you passed promise = true
declare module 'fastify' {
  interface FastifyInstance {
    mysql: MySQLPromisePool
  }
}

// if you passed promise = true, type = 'connection'
declare module 'fastify' {
  interface FastifyInstance {
    mysql: MySQLPromiseConnection
  }
}
```

#### MySQLRow 数据包

使用 mysql2 添加返回数据类型的能力 [RowData软件包](https://sidorares.github.io/node-mysql2/docs/documentation/typescript-examples#rowdatapacket)。 。 。 .

```js
const fastifyMysql, { MySQLRowDataPacket } from '@fastify/mysql'

const app = fastify();

app.register(fastifyMysql, {
  connectionString: "mysql://root@localhost/mysql",
});

app.get("/", async () => {
  const connection = app.mysql;

  // SELECT
  const [rows, fields] = await connection.query<MySQLRowDataPacket[]>(
    "SELECT 1 + 1 AS `test`;",
  );

  /**
   * @rows: [ { test: 2 } ]
   */
  return rows[0];
});
```

#### MySQL ResultSet页眉

使用 mysql2 添加返回数据类型的能力 [结果列表标题](https://sidorares.github.io/node-mysql2/docs/documentation/typescript-examples#resultsetheader)。 。 。 .

```js
const fastifyMysql, { MySQLResultSetHeader } from '@fastify/mysql'

const app = fastify();

app.register(fastifyMysql, {
  connectionString: "mysql://root@localhost/mysql",
});

app.get("/", async () => {
  const connection = app.mysql;
  const result = await connection.query<MySQLResultSetHeader>("SET @1 = 1");

  /**
   * @result: ResultSetHeader {
      fieldCount: 0,
      affectedRows: 0,
      insertId: 0,
      info: '',
      serverStatus: 2,
      warningStatus: 0,
      changedRows: 0
    }
   */
  return result
});
```

##### 是 MySQL Pool 语句

检查是否固定装饰的方法, Mysql 是类型 [MySQL Pool 游戏](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L32)

```typescript
const app = fastify();
app
  .register(fastifyMysql, {
    connectionString: "mysql://root@localhost/mysql",
  })
  .after(function (err) {
    if (isMySQLPool(app.mysql)) {
      const mysql = app.mysql
      mysql.getConnection(function (err, con) {
        con.release();
      });
      mysql.pool.end();
    }
  })
```

##### 是 MySQLPromise Pool 语句

检查是否固定装饰的方法, Mysql 是类型 [MySQLPromise 波尔语](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L43)

```typescript
app
  .register(fastifyMysql, {
    promise: true,
    connectionString: "mysql://root@localhost/mysql",
  })
  .after(async function (err) {
    if (isMySQLPromisePool(app.mysql)) {
      const mysql = app.mysql
      const con = await mysql.getConnection();
      con.release();
      mysql.pool.end();
    }
  });
```

##### 是 MySQLC 连接

检查是否固定装饰的方法, Mysql 是类型 [MySQLC 连接](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L28)

```typescript
app
  .register(fastifyMysql, {
    type: "connection",
    connectionString: "mysql://root@localhost/mysql",
  })
  .after(async function (err) {
    if (isMySQLConnection(app.mysql)) {
      const mysql = app.mysql
      mysql.connection.end();
    }
  });
```

##### 是 MySQLPromise 连接

检查是否固定装饰的方法, Mysql 是类型 [MySQLPromise 连接](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L36)

```typescript
app
  .register(fastifyMysql, {
    type: "connection",
    promise: true,
    connectionString: "mysql://root@localhost/mysql",
  })
  .after(async function (err) {
    if (isMySQLPromiseConnection(app.mysql)) {
      const mysql = app.mysql
      mysql.connection.end();
    }
  });
```

## 承认

这个项目由下列各方慷慨赞助:

-   [临近格式](https://nearform.com/)

过去提案国:

-   莱兹

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/mysql/LICENSE)。 。 。 .

## 常见问题

### @fastify/mysql 是什么？

快速化 Mysql 连接插件

### 如何安装 @fastify/mysql？

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

### @fastify/mysql 支持 TypeScript 吗？

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

### @fastify/mysql 支持 ESM 还是 CommonJS？

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

### @fastify/mysql 可以商用吗？

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

### @fastify/mysql 的下载量有多少？

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

### @fastify/mysql 还在维护吗？

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

