egg-mysql
:GITHUB传送门
一、配置
- 安装
egg-mysql
npm install egg-mysql -S
- 在
添加配置代码如下src/config/plugin.ts
export default { …… mysql: { enable: true, package: 'egg-mysql', } …… } as EggPlugin;
- 在
添加配置代码如下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
语句如下:
- 创建数据库,且编码为
utf8
- 创建数据表,且存在自增主键
、字符串字段id
name
create table test( id int not null auto_increment primary key, name varchar(100) not null );
- 向表中新增一条测试数据
三、注入
在
controller
中注入,代码如下
import { get, post } from 'midway';
import { Context, controller, inject, provide, plugin } from 'midway';
@provide()
@controller('/auth')
export class AuthController {
……
@plugin()
mysql;
……
}
接下来就可以通过
this.mysql
愉快的使用了
四、基础操作
- 条件查询,方法一
const result = await this.mysql.get("test", { id: 1 }) if (result != null) { console.log(result.name); }
- 条件查询,方法二
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); }
- 新增
- 修改,方法一
const result = await this.mysql.update('test', { id: 2, name: 'ella' }); console.log(result);
- 修改,方法二
const result = await this.mysql.query('update test set name = ? where id = ?', ["yooyea", 2]); console.log(result);
- 删除
let result = await this.mysql.delete('test', { id: 2 }); console.log(result);
- 执行原生SQL
const sql = 'select * from test limit ?' const values = [10] this.mysql.query(sql, values).then((res:any)=>{ console.log(res); })
- 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; }