阅读量:4
在egg.js中使用MySQL的步骤如下:
- 首先安装MySQL的驱动包
egg-mysql,可以通过npm安装:
$ npm install egg-mysql --save
- 在
config/plugin.js配置文件中启用MySQL插件:
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
- 在
config/config.default.js配置文件中配置MySQL连接信息:
exports.mysql = {
client: {
host: 'localhost',
port: '3306',
user: 'root',
password: 'password',
database: 'test',
},
};
- 在controller中使用MySQL服务:
const Controller = require('egg').Controller;
class UserController extends Controller {
async index() {
const { ctx } = this;
const user = await this.app.mysql.get('user', { id: 1 });
ctx.body = user;
}
async create() {
const { ctx } = this;
const result = await this.app.mysql.insert('user', { name: 'Alice', age: 18 });
ctx.body = result;
}
async update() {
const { ctx } = this;
const result = await this.app.mysql.update('user', { id: 1, age: 20 });
ctx.body = result;
}
async destroy() {
const { ctx } = this;
const result = await this.app.mysql.delete('user', { id: 1 });
ctx.body = result;
}
}
module.exports = UserController;
这样就可以在Egg.js中使用MySQL进行数据库操作了。
以上就是关于“egg中mysql的用法是什么”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm