安装
1 | $ npm i egg-mysql --save |
egg 的 MySQL 插件,支持egg 应用访问 MySQL 数据库。
本插件基于ali-rds,具体用法可以参考ali-rds文档。
更改${app_root}/config/plugin.js
以启用 MySQL 插件:
1 | exports.mysql = { |
配置数据库信息${app_root}/config/config.default.js
:
简单的数据库实例
1 | exports.mysql = { |
用法:
1 | app.mysql.query(sql, values); // you can access to simple database instance by using app.mysql. |
多数据库实例
1 | exports.mysql = { |
用法:
1 | const client1 = app.mysql.get('db1'); |
CRUD 用户指南
插入
1 | // 插入 |
读
1 | // 获取 |
更新
1 | // 按主键 ID 更新,并刷新 |
删除
1 | const result = yield app.mysql.delete('table-name', { |
交易
手动
- 优势:
beginTransaction
,commit
或者rollback
可以完全由开发者控制 - 缺点:手写代码较多,忘记捕捉错误或清理会导致严重的bug。
1 | const conn = yield app.mysql.beginTransaction(); |
自动控制:有作用域的事务
接口:
1
*beginTransactionScope(scope, ctx)
scope
:一个generatorFunction,它将执行这个事务的所有sqls。ctx
: 当前请求的上下文对象,它会确保即使在嵌套事务的情况下,一个请求中同时也只有一个活动事务。
优点:好用,就好像你的代码里没有事务一样。
缺点:所有交易都会成功或失败,无法精确控制
1 | const result = yield app.mysql.beginTransactionScope(function* (conn) { |
进步
自定义SQL拼接
1 | const results = yield app.mysql.query('update posts set hits = (hits + ?) where id = ?', [1, postId]); |
文字
如果要在 mysql 中调用文字或函数,可以使用Literal
.
内部文字
- NOW():数据库系统时间,可以通过
app.mysql.literals.now
.
1 | yield app.mysql.insert(table, { |
自定义文字
下面的demo展示了如何CONCAT(s1, ...sn)
在mysql中调用函数进行字符串拼接。
1 | const Literal = app.mysql.literals.Literal; |