@fastify/mysql

中文文档
5.0.5发布于 2026/10/15MITTypeScriptCommonJS构建来源已验证近 30 天下载 3.6万

快速化 Mysql 连接插件

中文使用文档
文档目录8 节
  1. 安装
  2. 兼容性
  3. 使用量
  4. 集合选项
  5. 命名实例范围
  6. 类型脚本
  7. 承认
  8. 许可证

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

CI NPM version neostandard javascript style

快速化 MySQL 连接插件; 您可以通过此程序在服务器的每个部分共享相同的 MySQL 连接池 . 盖下 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 政策 更多细节.

使用量

添加到您的项目 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

示例

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

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 组合。如果你不通过 connectionString,在插件中注册的每个 MySQL 选项都会转发到 mysql2.createPool()数字 :

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数字 :

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

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

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 显示四种不同类型的客户端, 我们没有指定您的打字方式 。 您需要按照下面的例子指定类型 .

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软件包。 。 。 .

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 添加返回数据类型的能力 结果列表标题。 。 。 .

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 游戏

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 波尔语

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 连接

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 连接

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();
    }
  });

承认

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

过去提案国:

  • 莱兹

许可证

许可证根据 麻省理工学院。 。 。 .

版本与发布记录

@fastify/mysql 共发布 13 个版本,首次发布于 2022/04/27;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.0.5latest2026/10/1530 天前
5.0.42026/10/091 个月前
5.0.32026/08/083 个月前
5.0.22025/01/121.8 年前
5.0.12024/09/212 年前
5.0.0next2024/09/062 年前

关于 @fastify/mysql 的常见问题

@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 和提交记录判断。