egg中mysql的用法是什么

996
2024/4/17 9:27:04
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在egg.js中使用MySQL的步骤如下:

  1. 首先安装MySQL的驱动包egg-mysql,可以通过npm安装:
$ npm install egg-mysql --save
  1. config/plugin.js配置文件中启用MySQL插件:
exports.mysql = {
  enable: true,
  package: 'egg-mysql',
};
  1. config/config.default.js配置文件中配置MySQL连接信息:
exports.mysql = {
  client: {
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: 'password',
    database: 'test',
  },
};
  1. 在controller中使用MySQL服务:
const Controller = require('egg').Controller;

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const user = await this.app.mysql.get('user', { id: 1 });
    ctx.body = user;
  }

  async create() {
    const { ctx } = this;
    const result = await this.app.mysql.insert('user', { name: 'Alice', age: 18 });
    ctx.body = result;
  }

  async update() {
    const { ctx } = this;
    const result = await this.app.mysql.update('user', { id: 1, age: 20 });
    ctx.body = result;
  }

  async destroy() {
    const { ctx } = this;
    const result = await this.app.mysql.delete('user', { id: 1 });
    ctx.body = result;
  }
}

module.exports = UserController;

这样就可以在Egg.js中使用MySQL进行数据库操作了。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 怎么查看mysql的安装路径