egg-mysql访问 MySQL 数据库(egg-mysql篇)

注意事项:
egg.js实现思路:符合Router -> Controller -> Service -> MySQL模式(Config配置)

1.首先安装egg-mysql

$ npm i --save egg-mysql

2.开启插件

// config/plugin.js

'use strict';
exports.mysql = {
  enable: true,
  package: 'egg-mysql',
};

3.在 config/config.${env}.js 配置各个环境的数据库连接信息(建议在config/config.default.js里配置)

  • 以下数据库相关密码端口号等信息自行修改
// config/config.default.js

'use strict';

module.exports = appInfo => {

  const config = exports = {};

  config.mysql = {
    client: {
      // host
      host: 'localhost',
      // 端口号
      port: '3306',
      // 用户名
      user: 'root',
      // 密码
      password: '123456',
      // 数据库名
      database: 'test',
    },
    // 是否加载到 app 上,默认开启
    app: true,
    // 是否加载到 agent 上,默认关闭
    agent: false,
  };

  return {
    ...config
  };

};

4.新建配置service

// app/service/user.js

'use strict';

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

class UserService extends Service {
  async find() {
  // "users" 为test数据库数据表名
    const user = await this.app.mysql.query('select * from users', '');
    return { user };
  }
}

module.exports = UserService;

5.配置controller

// app/controller/home.js

'use strict';

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

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    const user = await ctx.service.user.find();
    ctx.body = user;
  }
}

module.exports = HomeController;

6.配置router.js

//app/router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
 
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
};

7.浏览器中打开http://localhost:7001/,即可出现数据库中users数据表中数据

~end

番外篇(service,controller,router中的对应关系)

egg-mysql访问 MySQL 数据库(egg-mysql篇)_第1张图片

~end

你可能感兴趣的:(Node.Js_note,egg-mysql,egg.js,MySQL)