推荐答案
在 Fastify 中与 MySQL 集成可以通过使用 fastify-mysql 插件来实现。以下是一个简单的示例代码:
// www.javascriptcn.com code example
const fastify = require('fastify')({ logger: true });
const mysql = require('mysql2/promise');
fastify.register(require('fastify-mysql'), {
promise: true,
connectionString: 'mysql://user:password@localhost/database'
});
fastify.get('/users', async (request, reply) => {
const connection = await fastify.mysql.getConnection();
const [rows, fields] = await connection.query('SELECT * FROM users');
connection.release();
return rows;
});
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info('Server listening on http://localhost:3000');
});本题详细解读
1. 安装依赖
首先,你需要安装 fastify-mysql 和 mysql2 依赖:
npm install fastify-mysql mysql2
2. 配置 Fastify 与 MySQL 集成
在 Fastify 应用中,使用 fastify-mysql 插件来集成 MySQL。你需要提供一个连接字符串,其中包含数据库的用户名、密码、主机和数据库名称。
fastify.register(require('fastify-mysql'), {
promise: true,
connectionString: 'mysql://user:password@localhost/database'
});3. 使用 MySQL 连接
在路由处理函数中,你可以通过 fastify.mysql.getConnection() 获取一个 MySQL 连接。然后使用该连接执行 SQL 查询。
fastify.get('/users', async (request, reply) => {
const connection = await fastify.mysql.getConnection();
const [rows, fields] = await connection.query('SELECT * FROM users');
connection.release();
return rows;
});4. 释放连接
在查询完成后,务必调用 connection.release() 来释放连接,以避免连接池耗尽。
5. 启动服务器
最后,启动 Fastify 服务器并监听指定端口。
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info('Server listening on http://localhost:3000');
});通过以上步骤,你可以轻松地在 Fastify 应用中集成 MySQL 数据库,并执行查询操作。