$ npm i --save egg-mysql
config/plugin.js文件内容
由
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
};
修改为:
// config/plugin.js
'use strict';
module.exports = {
//mysql
mysql:{
enable:true,
package:'egg-mysql'
}
};
CREATE TABLE users
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(32) DEFAULT NULL,
pwd
varchar(32) DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
config.mysql = {
//database configuration
client:{
//host
host:'localhost',
//port
port:'3306',
//username
user:'root',
//password
password:'123456',
//database
database:'egg'
},
//load into app,default is open //加载到应用程序,默认为打开
app:true,
//load into agent,default is close //加载到代理中,默认值为“关闭”
agent:false,
};
// app/service/user.js
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async findAll() {
const user = await this.app.mysql.query('select * from users', '');
return { user };
}
async findById(id) {
const user = await this.app.mysql.query('select * from users where id=?', id);
return { user };
}
async insert(obj) {
const user = await this.app.mysql.insert('users',obj)
return { user };
}
async update(obj) {
const user = await this.app.mysql.update('users',obj)
return { user };
}
async deleteById(id) {
const user = await this.app.mysql.delete('users', { id: id});
return { user };
}
}
module.exports = UserService;
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx } = this;
const user = await ctx.service.user.find();
ctx.body = user;
}
async findAll() {
const user = await this.ctx.service.user.findAll();
this.ctx.body = user;
}
async findOne() {
const {id} = this.ctx.params
const user = await this.ctx.service.user.findById(id);
this.ctx.body = user;
}
async insert() {
const { name, pwd } = this.ctx.request.body
const obj={
"name":name,
"pwd":pwd
}
const user = await this.ctx.service.user.insert(obj);
this.ctx.body = user;
}
async update() {
const { id,name, pwd } = this.ctx.request.body
const obj={
"id":id,
"name":name,
"pwd":pwd
}
const user = await this.ctx.service.user.update(obj);
this.ctx.body = user;
}
async delete() {
const {id} = this.ctx.params;
const user = await this.ctx.service.user.deleteById(id);
this.ctx.body = user;
}
}
module.exports = HomeController;
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/findAll', controller.home.findAll);
router.get('/findOne/:id', controller.home.findOne);
router.post('/insert', controller.home.insert);
router.post('/update', controller.home.update);
router.get('/delete/:id', controller.home.delete);
};
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://onefire.blog.csdn.net/article/details/122557464
内容来源于网络,如有侵权,请联系作者删除!