而在Node.js生态系统中,Egg.js作为一个企业级Node.js框架,以其高度的可扩展性、内置的中间件机制和丰富的插件支持,进一步简化了开发流程,提升了开发效率
当涉及到数据库操作时,MySQL作为一个成熟、稳定的关系型数据库管理系统,依然是众多开发者的首选
本文将详细讲解如何使用Egg.js高效地操作MySQL数据库,涵盖从环境搭建到实战应用的全过程
一、环境搭建 1. 安装Node.js和npm 首先,确保你的开发环境中已经安装了Node.js和npm(Node Package Manager)
你可以通过访问Node.js官方网站下载并安装最新版本的Node.js,npm会随Node.js一起安装
2. 创建Egg.js项目 使用Egg.js官方提供的脚手架工具`egg-init`可以快速创建一个新的Egg.js项目
打开终端,执行以下命令: bash npm install egg-init -g egg-init egg-example --type=simple cd egg-example npm install 这将创建一个名为`egg-example`的新项目,并进入项目目录安装依赖
3. 安装MySQL和mysql2模块 接下来,你需要在本地安装MySQL数据库,并配置好数据库用户和密码
然后,在项目中安装`mysql2`模块,它是Node.js的一个MySQL客户端库,提供了对MySQL数据库的高效访问
bash npm install mysql2 --save 4. 配置Egg.js连接MySQL 在Egg.js项目中,配置文件通常位于`config/`目录下
为了连接MySQL数据库,你需要在`config/config.default.js`中添加数据库配置信息,或者创建一个专门的数据库配置文件,如`config/config.local.js`(用于本地开发环境)
javascript // config/config.default.js 或 config/config.local.js exports.mysql ={ client:{ type: mysql, host: localhost, // 数据库地址 port: 3306,// 数据库端口 database: testdb, // 数据库名 username: root,// 数据库用户名 password: password, // 数据库密码 charset: utf8mb4, }, app: true, agent: false, }; 二、使用Egg.js操作MySQL 1. 创建Service层 在Egg.js中,Service层负责业务逻辑的处理,通常包括与数据库的交互
你可以通过创建一个Service来封装对MySQL数据库的操作
在`app/service/`目录下创建一个新的Service文件,例如`user.js`: javascript // app/service/user.js const{ Service} = require(egg); class UserService extends Service{ async getUserById(id){ const{ app} = this; const{ mysql} = app.config; const{ client} = mysql; // 使用mysql2库的promise接口执行查询 const【rows】 = await client.execute(SELECT - FROM users WHERE id = ?, 【id】); return rows【0】 || null; } async createUser(username, password){ const{ app} = this; const{ mysql} = app.config; const{ client} = mysql; const【result】 = await client.execute(INSERT INTO users(username, password) VALUES(?, ?),【username, password】); return result.insertId; // 返回插入的ID } // 可以继续添加其他数据库操作方法... } module.exports = UserService; 2. 在Controller中调用Service Controller层负责处理HTTP请求,并将请求转发给相应的Service进行处理
在`app/controller/`目录下创建一个新的Controller文件,例如`user.js`: javascript // app/controller/user.js const{ Controller} = require(egg); class UserController extends Controller{ async getUser(){ const{ ctx} = this; const id = ctx.params.id; const user = await ctx.service.user.getUserById(id); ctx.body = user; } async createUser(){ const{ ctx} = this; const{ username, password} = ctx.request.body; const userId = await ctx.service.user.createUser(username, password); ctx.body ={ userId}; } // 可以继续添加其他HTTP请求处理方法... } module.exports = UserController; 3. 配置路由 在`app/router.js`文件中配置路由,将HTTP请求映射到相应的Controller方法上
javascript // app/router.js module.exports = app =>{ const{ router, controller} = app; router.get(/user/:id, controller.user.getUser); router.post(/user, controller.user.createUser); }; 三、实战应用与优化 1. 处理异步错误 在实际开发中,处理异步操作中的错误至关重要
你可以使用`try...catch`语句来捕获并处理错误
javascript // 修改UserService中的方法以处理错误 class UserService extends Service{ async getUserById(id){ try{ const{ app} = this; const{ mysql} = app.config; const{ client} = mysql; const【rows】 = await client.execute(SELECT - FROM users WHERE id = ?, 【id】); return rows【0】 || null; } catch(error){ // 处理错误,例如记录日志或返回错误信息 console.error(Error fetching user:, error); throw error; // 重新抛出错误以便上层处理 } } // 其他方法类似处理... } 2. 使用事务 在处理需要保证数据一致性的业务逻辑时,事务是不可