• 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 }

    数据库添加数据成功

  • 相关阅读:
    DFS&BFS
    最长上升非降子序列的长度动态规划
    模运算的基本性质
    codeforces 776C Molly's Chemicals(连续子序列和为k的次方的个数)
    D. String Game 二分加字符串匹配
    C
    hdu1556Color the ball线段树区间更新
    自动化测试
    自动化测试工具学习-selenium
    线程池
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/10556157.html
Copyright © 2020-2023  润新知