eggjs增删改查MySQL_egg.js的基本使用和调用数据库的方法示例

首先,整个项目的创建命令:

npm i egg-init -g //安装egg

egg-init egg-example --type=simple //初始化一个egg模板例子 后面的type跟的是模板类型这里是简单的

cd egg-example//进入例子

npm i //安装依赖

可以去官方教程查看基本配置的讲解。

直接说使用,简单看过Egg的文档,官方文档对于入门还是很实用的,再配合一些别人的攻略很容易入门上手就可以使用。

首先router.js:

'use strict';

/**

* @param {Egg.Application} app - egg application

*/

module.exports = app => {

const { router, controller } = app;

router.get('/', controller.home.index);

router.get('/custom',controller.customController.custonIndex); //自定义controller的路由

};

router.js中定义了我们的路由规则,所有的请求都会通过这个路由规则去找对应的Controller,这样也可以做到统一管控(如同前端初始化所有组件吧)。

接下来就是Controller控制层:

'use strict';

const Controller = require('egg').Controller;

class CustomController extends Controller {

async custonIndex() { //注意这里要定义成异步方法防止请求被阻塞

//let {id} = this.ctx.params; // 获取路由参数

//let {name} = this.ctx.query; // 获取用户入参

let options = {id:'5', name:2}

let info = await this.ctx.service.customService.getInfo(options);//调用Service层传参

处理,返回结果赋值

this.ctx.body = {

code: 200,

data: info

};//返回体

this.ctx.status = 200;

}

}

module.exports = CustomController;

发送请求会调用Controller中的方法,Controller中主要工作是接受用户的参数并进行处理,然后将处理好的参数发送给Service层,然后把Service的结果返回给用户。

其中对参数的处理包括但不仅限于参数校验和参数拼装,当然也可以直接返回不走Service,都在Controller层做处理,但是不建议这样做。

服务层(Service):

const Service = require('egg').Service;

class CustimService extends Service {

async getInfo(options) {

const results = await this.app.mysql.select('test',{id:5});

return results[0].name;

}

}

module.exports = CustimService;

Service层拿到Controller层的数据之后,根据条件执行对数据库或者其他操作,最终将结果返回,一个请求的简单流程就算是完成了

配置MySQL在egg-project\config\config.default.js里面,直接放上我的配置,具体起她的数据库配置方法可以自查。

'use strict';

module.exports = appInfo => {

const config = exports = {

mysql:{

// 单数据库信息配置

client: {

// host

host: '44.44.44.44',

// 端口号

port: '3306',

// 用户名

user: 'mysq',

// 密码

password: '359359',

// 数据库名

database: 'mysql_db',

},

// 是否加载到 app 上,默认开启

app: true,

// 是否加载到 agent 上,默认关闭

agent: false,

}

};

// use for cookie sign key, should change to your own and keep security

config.keys = appInfo.name + '_17792_5967';

// add your config here

config.middleware = [];

return config;

};

这样,你就打通了egg和数据库之间的基本操作了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值