03-egg如何使用-mysql

3 篇文章 1 订阅

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';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厚渡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值