您当前的位置:首页 > 计算机 > 软件应用 > 数据库 > MySQL

egg-mysql 用于 egg 框架的阿里云 rds 客户端

时间:12-14来源:作者:点击数:

egg-mysql 是一个用于 egg 框架的阿里云 rds 客户端,支持 mysql portocal。

安装

$ npm i egg-mysql --save

Egg 的 MySQL Plugin,支持 egg 应用访问 MySQL 数据库。本插件基于 ali-rds( github /ali-sdk/ali-rds),具体用法可参考 ali-rds( github /ali-sdk/ali-rds) 文档。

配置

更改 ${app_root}/config/plugin.js 以启用 MySQL 插件:

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

配置数据库信息 ${app_root}/config/config.default.js

简单的数据库实例

exports.mysql = {
  // database configuration
  client: {
    // host
    host: 'mysql.com',
    // port
    port: '3306',
    // username
    user: 'test_user',
    // password
    password: 'test_password',
    // database
    database: 'test',    
  },
  // load into app, default is open
  app: true,
  // load into agent, default is close
  agent: false,
};

用法:

app.mysql.query(sql, values);
// you can access to simple database instance by using app.mysql.

多数据库实例

exports.mysql = {
  clients: {
    // clientId, access the client instance by app.mysql.get('clientId')
    db1: {
      // host
      host: 'mysql.com',
      // port
      port: '3306',
      // username
      user: 'test_user',
      // password
      password: 'test_password',
      // database
      database: 'test',
    },
    // ...
  },
  // default configuration for all databases
  default: {

  },

  // load into app, default is open
  app: true,
  // load into agent, default is close
  agent: false,
};

用法:

const client1 = app.mysql.get('db1');
client1.query(sql, values);

const client2 = app.mysql.get('db2');
client2.query(sql, values);

CRUD 用户指南

创建

// insert
const result = yield app.mysql.insert('posts', { title: 'Hello World' });
const insertSuccess = result.affectedRows === 1;

查询

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

更新

// 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 = yield app.mysql.update('posts', row);
const updateSuccess = result.affectedRows === 1;

删除

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

事务

手动

  • 优势:beginTransactioncommit 或者 rollback 可以完全由开发者控制
  • 缺点:手写代码较多,忘记捕捉错误或清理会导致严重的 bug。
const conn = yield app.mysql.beginTransaction();

try {
  yield conn.insert(table, row1);
  yield conn.update(table, row2);
  yield conn.commit();
} catch (err) {
  // error, rollback
  yield conn.rollback(); // rollback call won't throw err
  throw err;
}

自动控制:有作用域的事务

  • 接口:*beginTransactionScope(scope, ctx)
    • scope:一个 generatorFunction,它将执行这个事务的所有 sqls。
    • ctx:当前请求的上下文对象,它会确保即使在嵌套事务的情况下,一个请求中同时也只有一个活动事务。
  • 优点:好用,就好像你的代码里没有事务一样。
  • 缺点:所有交易都会成功或失败,无法精确控制
const result = yield app.mysql.beginTransactionScope(function* (conn) {
  // don't commit or rollback by yourself
  yield conn.insert(table, row1);
  yield conn.update(table, row2);
  return { success: true };
}, ctx); // ctx is the context of current request, access by `this.ctx`.
// if error throw on scope, will auto rollback

高级用法

自定义 SQL 拼接

const results = yield app.mysql.query('update posts set hits = (hits + ?) where id = ?', [1, postId]);

Literal 字面量

如果要在 mysql 中调用文字或函数,可以使用 Literal

内部 Literal
  • NOW():数据库系统时间,可以通过 app.mysql.literals.now
yield app.mysql.insert(table, {
  create_time: app.mysql.literals.now
});

// INSERT INTO `$table`(`create_time`) VALUES(NOW())
自定义 Literal

下面的 demo 展示了如何 CONCAT(s1, ...sn) 在 mysql 中调用函数进行字符串拼接。

const Literal = app.mysql.literals.Literal;
const first = 'James';
const last = 'Bond';
yield app.mysql.insert(table, {
  id: 123,
  fullname: new Literal(`CONCAT("${first}", "${last}"`),
});

// INSERT INTO `$table`(`id`, `fullname`) VALUES(123, CONCAT("James", "Bond"))
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐