egg 连接mysql 在mysql 插入数据
1。配置mysql
exports.mysql = { enable: true, package: 'egg-mysql' };
'use strict'; module.exports = appInfo => { const config = exports = {}; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1551971762613_5533'; // add your config here config.middleware = []; config.mysql = { client: { host: 'localhost', port: '3306', user: 'root', password: 'root', database:'cms-api' } }, config.security= { csrf: { enable: false, } } return config; };
2.services
user.js
const Service = require('egg').Service; class UserService extends Service { async create(user) { let {app}=this; let result = await app.mysql.insert('user', user ); return result; } } module.exports = UserService;
3.Controller
user.js
const Controller = require('egg').Controller; class UserController extends Controller { async create() { const { ctx,service} = this; let user =ctx.request.body; let result = await service.user.create(user); console.log(result); this.ctx.body=result; if(result.affectedRows === 1) { this.ctx.body ={ code:0, data:result.insertId } }else { this.ctx.body ={ code:1, data:'用户添加失败' } } } } module.exports = UserController;
/ 判断插入成功
const insertSuccess = result.affectedRows === 1;
result的打印解果
OkPacket { fieldCount: 0, affectedRows: 1, insertId: 0, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0 }
数据库添加数据成功
越努力越幸运