1、安装egg-mysql插件
yarn add egg-mysql -S
2、修改app/config/plugin.js
增加以下内容
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
3、修改app/config/config.default.js
增加以下内容
config.mysql = {
app: true, // 是否挂载到app下
agent: false, // 是否挂载到代理下
client: { // 链接数据库信息
host: '127.0.0.1',
port: '3306',
user: 'root',
password: 'root@547548847',
database: 'test-egg',
},
};
4、在test-egg数据库下建立girls表
5、在app/service下新建girls.js,具体内容如下:
'use strict';
const Service = require('egg').Service;
class girlsService extends Service {
async addGirl() {}
async delGirl() {}
async updateGirl() {}
async getGirls() {}
}
module.exports = girlsService;
6、在app/controller下新建girlsManage.js,具体内容如下:
'use strict';
const Controller = require('egg').Controller;
class GirlManage extends Controller {
async addGirl() {
const { ctx } = this;
ctx.body = '添加女孩';
}
async delGirl() {
const { ctx } = this;
ctx.body = '删除女孩';
}
async updateGirl() {
const { ctx } = this;
ctx.body = '修改女孩';
}
async getGirls() {
const { ctx } = this;
ctx.body = '查询女孩';
}
}
module.exports = GirlManage;
7、配置新增新路由app/router.js 修改如下:
router.post('/addgirl', controller.girlsManage.addGirl);
router.post('/delgirl', controller.girlsManage.delGirl);
router.post('/updategirl', controller.girlsManage.updateGirl);
router.get('/getgirls', controller.girlsManage.getGirls);
8、实现查询girls表,修改app/service/girls.js和app/controller/girlsManage.js
girls.js
async getGirls() {
try {
const app = this.app;
const res = await app.mysql.select('girls');
return res;
} catch (error) {
console.log(error);
return null;
}
}
girlsManage.js
async getGirls() {
const { ctx } = this;
const res = await ctx.service.girls.getGirls();
ctx.body = '查询女孩:' + JSON.stringify(res);
}
9、运行预览