egg数据库配置
框架提供egg-mysql插件来访问Mysql数据库。这个插件可以访问普通的Mysql数据库,也可以访问基于MySQL协议的在线数据库
安装与配置
// 安装对应的插件egg-mysql
$ npm i egg-mysql --save
// 安装成功后需要开启插件
// config/plugin.js
exports.mysql = {
enabel: true,
package: 'egg-mysql'
}
// 在 config/config.default.js配置各个环境的数据库信息
// 单数据库源配置
exports.mysql = {
// 但数据库配置信息
client: {
host: 'mysql.com', // host
port: '3306', // 端口号
user: 'user', // 用户名
password: 'password', // 密码
database: 'databaseName', // 数据库名
}
app: true, // 是否加载到app上,默认开启
agent: false, // 是否加载到agent上,默认关闭
}
// 使用方式
await this.app.mysql.query(sql, values) // 但实例可以直接通过this.app.mysql 访问
// 多数据源配置
exports.mysql = {
clients: {
// clientId,获取client实例,需要通过app.mysql.get('clientId') 获取
db1: {
host: 'mysql.com',
port: '3306',
user: 'user1',
password: 'password1'
database: 'database1',
},
db2: {
host: 'mysql2.com',
port: '3307',
user: 'user2',
password: 'password2',
database: 'database2',
}
// ... db3,db4
}
// 所有数据库配置的默认值
default: {
.....
},
app: true,
agent: false
}
// 使用方式
const client1 = this.app.mysql.get('db1');
await client1.query(sql, values);
const client2 = this.app.mysql.get('db2');
await client2.query(sql, values);
编写CRUD语句
crud是指在做计算处理时的增加(Create)、读取(Retrieve)、更新(Update)和删除(Delete)几个单词的首字母简写。crud主要被用在描述软件系统中数据库或者持久层的基本操作功能。
crate
可以直接使用insert方法插入一条记录insert('table_name', options)
· table_name: 数据库名
· options: 字段key,value传参
const result = await this.app.mysql.insert('posts', { title: 'hello world'})
=> INSERT INTO posts ('title') VALUE ('hello world');
console.log(result)
=> 返回操作数据信息,是一个对象
{
fieldCount: 0,
affectedRows: 1,
insertId: 3710,
serverStatus: 2,
warningCount: 2,
message: '',
protocol41: true,
changedRows: 0
}
// 判断是否插入成功
const insertSuccess = result.affectedRows === 1
Read
可以直接使用get方法或select方法获取一条或多条记录,select方法支持条件查询与结果的定制
// 查询一条数据
const post = await this.app.mysql.get('posts', {id: 12});
=> SELECT * FROM posts WHERE id = 12 LIMIT 0, 1;
// 查询全表
const post = await this.app.mysql.select('posts');
=> SELECT * FROM posts
// 条件查询和结果定制
const options = {
// WHERE 查询条件
where: { status: 'draft', author: ['author1', 'author2'] },
// 要查询的表字段
colums: ['author', 'title'],
// 排序方式
orders: [['created_at', 'desc'], ['id', 'desc']],
// 返回数据量
limit: 10,
// 数据偏移量(从第几条数据开始查询)
offset: 0
};
const results = await this.app.mysql.select('posts', options)
=> SELECT author, title FROM posts
WHERE suatus = 'draft' AND author IN('author1', 'author2')
ORDER BY created_at DESC, id DESC LIMIT 0, 10;
update
可以直接使用update方法更新数据库记录
const row = {
id: 123,
name: 'jack',
otherField: 'other field value', //其他的字段
modifiedAt: this.app.mysql.literals.now, // 更新修改时间为当前时间
}
const resutl = await this.app.mysql.update('posts', row);
=> UPDATE posts SET name='jack',modifiedAt = NOW() WHERE id = 1;
// 判断更新成功
const updateSuccess = result.affectedRows === 1;
// 如果主键是自定义ID名称,如custom_id,则需要在where里面配置
const row = {
name: 'jack',
otherField: 'other field value',
modifiedAt: this.app.mysql.literals.now,
}
const options = {
where: {
custom_id: 456
}
};
const result = await this.app.mysql update('posts', row, options);
=> UPDATE posts SET name='jack', modifiedAt= NOW() WHERE custom_id =456
Delete
const result = await this.app.mysql.delete('posts', {author: 'jack'});
=> DELETE FROM posts WHERE author = 'jack';
直接执行sql语句
插件本身也支持拼接与直接执行sql语句。使用query可以执行合法的sql语句
const sql = 'UPDATE posts SET name=jack';
const result = await this.app.mysql.query(sql)
=> UPDATE posts SET name = 'jack';