https://eggjs.org/zh-cn/tutorials/mysql.html
安装与配置
安装对应的插件 egg-mysql :
npm i --save egg-mysql
开启插件:
// config/plugin.js
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
在 config/config.${env}.js 配置各个环境的数据库连接信息。
单数据源
如果我们的应用只需要访问一个 MySQL 数据库实例,可以如下配置:
// config/config.${env}.js
exports.mysql = {
// 单数据库信息配置
client: {
// host
host: 'mysql.com',
// 端口号
port: '3306',
// 用户名
user: 'test_user',
// 密码
password: 'test_password',
// 数据库名
database: 'test',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
使用方式:
await app.mysql.query(sql, values); // 单实例可以直接通过 app.mysql 访问
多数据源
如果我们的应用需要访问多个 MySQL 数据源,可以按照如下配置:
exports.mysql = {
clients: {
// clientId, 获取client实例,需要通过 app.mysql.get('clientId') 获取
db1: {
// host
host: 'mysql.com',
// 端口号
port: '3306',
// 用户名
user: 'test_user',
// 密码
password: 'test_password',
// 数据库名
database: 'test',
},
db2: {
// host
host: 'mysql2.com',
// 端口号
port: '3307',
// 用户名
user: 'test_user',
// 密码
password: 'test_password',
// 数据库名
database: 'test',
},
// ...
},
// 所有数据库配置的默认值
default: {},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
使用方式:
const client1 = app.mysql.get(‘db1’);
await client1.query(sql, values);const client2 = app.mysql.get(‘db2’);
await client2.query(sql, values);
动态创建
我们可以不需要将配置提前申明在配置文件中,而是在应用运行时动态的从配置中心获取实际的参数,再来初始化一个实例。
// {app_root}/app.js
module.exports = (app) => {
app.beforeStart(async () => {
// 从配置中心获取 MySQL 的配置
// { host: 'mysql.com', port: '3306', user: 'test_user', password: 'test_password', database: 'test' }
const mysqlConfig = await app.configCenter.fetch('mysql');
app.database = app.mysql.createInstance(mysqlConfig);
});
};
Mysql语句
添加语句
// 插入 const result = await this.app.mysql.insert('posts', { title: 'Hello World' }); // 在 post 表中,插入 title 为 Hello World 的记录 => INSERT INTO `posts`(`title`) VALUES('Hello World'); 用法: const result = await this.app.mysql.insert('表名', { 字段: 值 }); 例子: const result = await this.app.mysql.insert('verification_code', { vemail: '1172824052@qq.com' });
更新语句
// 修改数据,将会根据主键 ID 查找,并更新 // 修改数据,将会根据主键 ID 查找,并更新 用法1: const row = { id: 123, name: 'fengmk2', otherField: 'other field value', // any other fields u want to update 其他更新字段 modifiedAt: this.app.mysql.literals.now, // `now()` on db server }; const result = await this.app.mysql.update('posts', row); // 更新 posts 表中的记录 => UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE id = 123 ; // 判断更新成功 const updateSuccess = result.affectedRows === 1; 例子: 用法二: // 如果主键是自定义的 ID 名称,如 custom_id,则需要在 `where` 里面配置 const row = { name: 'fengmk2', otherField: 'other field value', // any other fields u want to update 其他更新字段 modifiedAt: this.app.mysql.literals.now, // `now()` on db server }; // 自定义更新条件 const options = { where: { custom_id: 456 } }; const result = await this.app.mysql.update('posts', row, options); // 更新 posts 表中的记录 => UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE custom_id = 456 ; // 判断更新成功 const updateSuccess = result.affectedRows === 1; 例子: const row = { // 更新内容 vcode: code, v_start_time: new Date(), v_end_time: new Date(new Date().getTime() + 1000 * 60 * 3), }; const options = { where: { // 条件 vemail: request.email, }, }; const result = await this.app.mysql.update( "verification_code", row, options ); const updateSuccess = result.affectedRows === 1; console.log(updateSuccess); // 更新是否成功
查询语句
查询一条: const post = await this.app.mysql.get('posts', { id: 12 }); => SELECT * FROM `posts` WHERE `id` = 12 LIMIT 0, 1; 用法: const user = await this.app.mysql.get('表明', { id: 11 }); 例子: const user = await this.app.mysql.get('users', { id: 11 }); 查询全表: const results = await this.app.mysql.select('posts'); => SELECT * FROM `posts`; 查询结果 和 结果定制: const results = await this.app.mysql.select('posts', { // 搜索 post 表 where: { status: 'draft', author: ['author1', 'author2'] }, // WHERE 条件 columns: ['author', 'title'], // 要查询的表字段 orders: [['created_at','desc'], ['id','desc']], // 排序方式 limit: 10, // 返回数据量 offset: 0, // 数据偏移量 }); => SELECT `author`, `title` FROM `posts` WHERE `status` = 'draft' AND `author` IN('author1','author2') ORDER BY `created_at` DESC, `id` DESC LIMIT 0, 10;
删除
可以直接使用 delete 方法删除数据库记录。
const result = await this.app.mysql.delete('posts', {
author: 'fengmk2',
});
=> DELETE FROM `posts` WHERE `author` = 'fengmk2';