midway mysql egg-mysql 配置 基礎操作 增刪改查

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;
    }
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章