Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

【弃用】egg-mysql配置(无model方案)+CRUD操作+事务

egg-mysql配置

  • 进入项目目录,打开命令行

    • 安装egg-mysql数据库访问插件

      cnpm install egg-mysql -S 
      
  • 找到config/plugin.js

    • 添加下面的内容来开启插件
      mysql: {
          enable: true,
          package: 'egg-mysql'
      },
      
  • 配置数据库信息

    • 找到config/config.default.js

    • 对于单个数据库

      config.mysql = {
          client:{
              host: "127.0.0.1",
              port: "3306",
              user: "root",
              password: "123456",
              database: "book_list"
              //可选debug参数为true,可后台打印出数据库原生执行语句
          },
          app: true,
          agent: false,
      }
      
      • 获取执行方式
        await app.mysql.query(sql, values); 
        
      • 原生sql语句操作方式,为了防止sql注入,采用每个?匹配一个元素的方式(另有更方便的CRUD操作方式)
    • 多个数据库

      config.mysql = {
          client:{
              db1:{
                  五条信息
              },
              db2:{
                  五条信息
              },    
          },
          app: true,
          agent: false,
      }
      
      • 获取执行方式
        const client1 = app.mysql.get('db1');
        await client1.query(sql, values);
        
      • 原生sql语句操作方式

egg-mysql的CRUD操作

以 posts表 为例子

  • insert 插入数据

    const result = await this.app.mysql.insert('posts', { title: 'Hello World' });
    
    //判断是否成功
    const insertSuccess = result.affectedRows ===1;
    
  • get 查询数据

    • 查一条

      const data = await this.app.mysql.get('posts', { id: 12 });
      
    • 查全表

      const dataAll = await this.app.mysql.get('posts');
      
  • select 查询数据(支持条件查询和结果定制)

    const results = await this.app.mysql.select('posts', { 
      where: { status: 'draft', author: ['author1', 'author2'] },
      columns: ['author', 'title'], 
      orders: [['created_at','desc'], ['id','desc']],
      limit: 10,
      offset: 0,
    });
    
  • update 更新数据

    • 当主键是id时

      const row = {
        id: 123,
        name: 'fengmk2',
      };
      const result = await this.app.mysql.update('posts', row);
      const insertSuccess = result.affectedRows ===1;
      
    • 当主键是自定义的custom_id时

      const row = {
        name: 'fengmk2',
      };
      const options = {
        where: {
          custom_id: 456
        }
      };
      const result = await this.app.mysql.update('posts', row, options);
      const insertSuccess = result.affectedRows ===1;
      
  • delete 删除数据

    const result = await this.app.mysql.delete('posts', {
      author: 'fengmk2',
    });
    
  • count统计次数

    const result = await this.app.mysql.count('posts', {
      author: 'fengmk2',
    });
    

eggjs数据库事务

  • 手动控制

    const conn = await app.mysql.beginTransaction();
    
    try {
      await conn.insert(table, row1);  // 第一步操作
      await conn.update(table, row2);  // 第二步操作
      await conn.commit(); // 提交事务
    } catch (err) {
      // error, rollback
      await conn.rollback(); // 一定记得捕获异常后回滚事务!!
      throw err;
    }
    
  • 自动控制(不用自己提交,捕获回滚,报错)

    const result = await app.mysql.beginTransactionScope(async conn => {
      await conn.insert(table, row1); // 第一步操作
      await conn.update(table, row2); // 第二步操作
      return { success: true };
    }, ctx);
    

表达式 literals

  • 获取当前系统时间
    this.app.mysql.literals.now