egg-mysql操作数据库,实际开发中会使用 sequelize ORM来操作数据库,不会使用 sql语句来直接操作数据库;
egg-mysql作为了解即可。
egg-mysql文档 https://www.eggjs.org/zh-CN/tutorials/mysql#egg-mysql
安装 egg-mysql
yarn add egg-mysql
plugin.js配置
src/config/plugin.js
exports.mysql = {enable: true,package: 'egg-mysql',};
config.defaut.js配置
src/config/config.default.js 配置 mysql连接
config.mysql = {app: true, // 将 mysql挂载到 app下面, app.mysqlagent: false,client: {host: '127.0.0.1',port: '3306',user: 'root',password: 'root',database: 'qixiu',},};
- app: true, 将 mysql属性挂载到app下 this.app.mysql
Services查询数据库
app.mysql 查询数据库
'use strict';const { Service } = require('egg');const dbName = 'blog';class UserService extends Service {// 查询整张表async list() {const {mysql} = this.app;return await mysql.select(dbName);}// 查询一条数据async findOne(id) {const {mysql} = this.app;return await mysql.get(dbName, {id});}// 新增数据 insert intoasync add(params) {const {mysql} = this.app;return await mysql.insert(dbName, params);}// 新增数据 insert intoasync update(params) {const {mysql} = this.app;return await mysql.update(dbName, params);}// 删除数据 deleteasync del(id) {const {mysql} = this.app;return await mysql.delelte(dbName, {id});}}
Controller
'use strict';const { Controller } = require('egg');class UserController extends Controller {async list() {const {ctx} = this;const res = await ctx.service.user.list();ctx.body = {code: 0,data: res,};}// /api/list/23async findOne() {const {ctx} = this;const res = await ctx.service.user.findOne(ctx.params.id);ctx.body = {code: 0,data: res,};}// 新增数据,没有id insert intoasync add(params) {const {ctx} = this;const validateRule = {title: {type: 'string'},content: {type: 'string'}}ctx.validate(validateRule);// 插入一条数据const res = await ctx.service.user.add(ctx.request.body);ctx.body = {code: 0,data: res,};}// 新增数据,有id insert intoasync update(params) {const {ctx} = this;const validateRule = {id: {type: 'number'},title: {type: 'string'},content: {type: 'string'}}ctx.validate(validateRule);// put更新数据const res = await ctx.service.user.add(ctx.request.body);ctx.body = {code: 0,data: res,};}// 删除一条数据async del() {const {ctx} = this;const res = await ctx.service.user.del(ctx.params.id);ctx.body = {code: 204,};}}
put和 patch的区别
- put和 patch都是更新操作
- put要求前端提供的一定是一个完整的资源对象,如果你用了put,但却没有提供完整的UserInfo,那么缺了的那些字段应该被清空
- patch 局部更新,后端仅更新接收到的字段。
- PATCH:更新部分资源,非幂等,非安全
- PUT:更新整个资源,具有幂等性,非安全
幂等性:多次请求的结果和请求一次的结果一样
安全性:请求不改变资源状态
