midway mysql egg-mysql 配置 基础操作 增删改查

37 篇文章 1 订阅
3 篇文章 0 订阅

egg-mysqlGITHUB传送门

一、配置

  1. 安装egg-mysql
    npm install egg-mysql -S
    
  2. src/config/plugin.ts添加配置代码如下
    export default {
      ……
      mysql: {
        enable: true,
        package: 'egg-mysql',
      }
      ……
    } as EggPlugin;
    
  3. src/config/config.default.ts添加配置代码如下
    import { EggAppConfig, EggAppInfo, PowerPartial } from 'midway';
    export type DefaultConfig = PowerPartial<EggAppConfig>
    
    export default (appInfo: EggAppInfo) => {
      const config = <DefaultConfig> {};
      ……
      config.mysql = {
        // database configuration
        client: {
          // host
          host: '127.0.0.1',
          // port
          port: '3306',
          // username
          user: 'root',
          // password
          password: '123456',
          // database
          database: 'yoye',
        },
        //load into app,default is open //加载到应用程序,默认为打开
        app:true,
        //load into agent,default is close //加载到代理中,默认值为“关闭”
        agent:false,
      }
      
    ……
      return config;
    };
    

二、创建测试数据

在这里我们的mysql里是存在名为yoye的数据库,并且通过sql语句新建了test表,且存在一个name字段,新建数据库并初始化测试表SQL语句如下:

  1. 创建数据库,且编码为utf8
    CREATE DATABASE `yoye` CHARACTER SET utf8 COLLATE utf8_general_ci;
    
  2. 创建数据表,且存在自增主键id、字符串字段name
    create table test(
    	id int not null auto_increment primary key,
    	name varchar(100) not null
    );
    
  3. 向表中新增一条测试数据
    insert into test (name) values('yoye');
    

三、注入

controller中注入,代码如下

import { get, post } from 'midway';
import { Context, controller, inject, provide, plugin } from 'midway';

@provide()
@controller('/auth')
export class AuthController {
  ……
  @plugin()
  mysql;
  ……
}

接下来就可以通过this.mysql愉快的使用了

四、基础操作

  1. 条件查询,方法一
    const result = await this.mysql.get("test", { id: 1 })
    if (result != null) {
      console.log(result.name);
    }
    
  2. 条件查询,方法二
    const result = await this.mysql.select("test", {
      where: {
        name: ['yoye', 'test'], // 相当于 in
      },
      order: [['id', 'desc'], ['name', 'desc']]
    })
    if (result.length) {
      console.log(result[0].name);
    }
    
  3. 新增
    const result = await this.mysql.insert("test", { name: "lisa" })
    
  4. 修改,方法一
    const result = await this.mysql.update('test', { id: 2, name: 'ella' });
    console.log(result);
    
  5. 修改,方法二
    const result = await this.mysql.query('update test set name = ? where id = ?', ["yooyea", 2]);
    console.log(result);
    
  6. 删除
    let result = await this.mysql.delete('test', { id: 2 });
    console.log(result);
    
  7. 执行原生SQL
    const sql = 'select * from test limit ?'
    const values = [10]
    this.mysql.query(sql, values).then((res:any)=>{
      console.log(res);
    })    
    
  8. Mysql事务
    const conn = await this.mysql.beginTransaction();
    try {
      await conn.insert('test', { 'name': 'lisa' });
      await conn.update('test', { id: 2, name: 'ella' });
      await conn.commit();  //提交事务
      const result = await this.mysql.select("test", {})
      console.log(result);
    } catch (err) {
      await conn.rollback();//回滚事务
      throw err;
    }
    
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泡泡码客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值