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);
// 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'
});
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;
}
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
const results = yield app.mysql.query('update posts set hits = (hits + ?) where id = ?', [1, postId]);
如果要在 mysql 中调用文字或函数,可以使用 Literal。
yield app.mysql.insert(table, {
create_time: app.mysql.literals.now
});
// INSERT INTO `$table`(`create_time`) VALUES(NOW())
下面的 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"))
