安装
配置
plugin.js
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
config.default.js
config.mysql = {
app: true, // 是否将mysql挂载到app下
agent: false, // 是否挂载在代理下面
client: {
host: '127.0.0.1',
port: '3306',
user: 'root',
password: '0000mysql',
database: 'egg',
},
};
使用
问题
遇到的问题:
报错 nodejs.AppWorkerDiedError 怎么解决?
增删改查
service/user.js
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async lists() {
try {
const { app } = this;
// const res = await app.mysql.query(
// 'SELECT * FROM user',
// ''
// );
//查 user 表中全部
const res = await app.mysql.select('user');
// console.log('SELECT', res);
return res;
} catch (error) {
console.log('service/user.js/lists', error);
return null;
}
}
async detail(id) {
return {
id,
name: 'zhou',
age: 20,
};
}
async detail2(id) {
try {
const { app } = this;
// 查user 表中 的id
const res = await app.mysql.get('user', { id });
return res;
} catch (error) {
console.log('service/user.js/lists', error);
return null;
}
}
async add(params) {
try {
const { app } = this;
// 接收参数,给user 表中添加 数据
const res = await app.mysql.insert('user', params);
return res;
} catch (error) {
console.log('service/user.js/lists', error);
return null;
}
}
async edit(params) {
try {
const { app } = this;
// 接收参数,修改user 表中一对属性
const res = await app.mysql.update('user', params);
return res;
} catch (error) {
console.log('service/user.js/lists', error);
return null;
}
}
async delete(id) {
try {
const { app } = this;
// 删除
const res = await app.mysql.delete('user', { id });
return res;
} catch (error) {
console.log('service/user.js/lists', error);
return null;
}
}
}
module.exports = UserService;
controller 中调用
controller/user.js
async lists() {
// eslint-disable-next-line no-unused-vars
const { ctx, app } = this;
// console.log('app.mysql.query--------', app.mysql.query);
// await new Promise(resolve => {
// setTimeout(() => {
// resolve();
// }, 1500);
// });
const res = await ctx.service.user.lists();
// console.log('res0----', res0);
// const res = 'await ctx.service.user.lists';
ctx.body = res;
}
async detail2() {
const { ctx } = this;
const res = await ctx.service.user.detail2(ctx.params.id);
ctx.body = res;
}
async add() {
const { ctx } = this;
// const rule = {
// name: { type: 'string' },
// age: { type: 'number' },
// };
// ctx.validate(rule);
const res = await ctx.service.user.add(ctx.request.body);
// ctx.body = { status: 200, data: ctx.request.body };
ctx.body = { status: 200, data: res };
}
async edit() {
const { ctx } = this;
const res = await ctx.service.user.edit(ctx.request.body);
ctx.body = { status: 200, data: res };
}
async del() {
const { ctx } = this;
const res = ctx.service.user.delete(ctx.request.body.id);
ctx.body = { status: 200, data: res };
}
get 请求之外的操作测试:
添加
修改
删