egg链接数据库并实现基础的增、删、改、查

165 阅读1分钟

前置条件

  1. 本地数据库搭建完成
  2. 相关数据表导入

本地连接

1. egg-mysql

安装egg-mysql插件

npm add egg-mysql --save

2. 配置config

a. 开启插件

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

b. 配置链接数据库参数

config.mysql = {
    client: {
      // host
      host: '127.0.0.1',
      // port
      port: '3306',
      // username
      user: 'root',
      // password
      password: '534684120xue0359',
      // database
      database: 'account-book',
    },
    // load into app, default is open
    app: true,
    // load into agent, default is close
    agent: false,
 };

数据库操作

service

新建service目录 用来存放数据库相关的操作

示例

新建 service/user.js文件

const { Service } = require('egg');

class UserService extends Service {
  async user() {
    const { ctx, app } = this;
    const result = await app.mysql.select('user'); // 对数据库进行操作
    return result;
  }
}

基础操作

const result = await app.mysql.insert('posts', { title: 'Hello World' });

const result = await app.mysql.delete('table-name', {
  name: 'fengmk2',
});

// update by primary key ID, and refresh
const row = {
  id: 123,
  name: 'fengmk2',
  otherField: 'other field value',
  modifiedAt: app.mysql.literals.now, // `now()` on db server
};
const result = await app.mysql.update('posts', row);

// get
const post = await app.mysql.get('posts', { id: 12 });
// query
const results = await app.mysql.select('posts',{
  where: { status: 'draft' },
  orders: [['created_at','desc'], ['id','desc']],
  limit: 10,
  offset: 0
});

上一篇:用egg快速搭建service项目 - 掘金 (juejin.cn)