引言

框架提供了 egg-mysql 插件来访问 MySQL 数据库。这个插件既可以访问普通的 MySQL 数据库,也可以访问基于 MySQL 协议的在线数据库服务。

安装

1
cnpm i --save egg-mysql

插件配置:

config/plugin.js

1
2
3
4
exports.mysql = {
enable: true,
package: "egg-mysql",
};

数据配置

config/config.default.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
exports.mysql = {
// 单数据库信息配置
client: {
// 域名/ip地址
host: "localhost",
// 端口号
port: "3306",
// 用户名
user: "root",
// 密码
password: "12344321",
// 数据库名
database: "db_1811a",
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};

使用

从 MVC 的编程思想来看,我们应该在 service 服务中操作数据库
通过 this.ctx.app.mysql 来访问我们配置好的 egg-mysql
service/user.js

1
2
3
4
5
6
7
8
9
10
11
12
13
const { idCreator } = require("../utils");
const { Service } = require("egg");

class UserService extends Service {
async registry({ username, password }) {
const uid = idCreator(username);
const sql = `insert into login (uid,username,password) values (?,?,?)`;
const params = [uid, username, password];
return await this.ctx.app.mysql.query(sql, params);
}
}

module.exports = UserService;