egg 连接mysql 在mysql 插入数据
Posted 1点
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
数据库添加数据成功
以上是关于egg 连接mysql 在mysql 插入数据的主要内容,如果未能解决你的问题,请参考以下文章