Eggjs是一个基于Node.js的企业级开发框架,它提供了一站式的解决方案。其中,egg-mysql是eggjs中操作mysql数据库的插件,它包含了许多常用的mysql操作方法。本文将讲解如何使用egg-mysql插件中的delete方法来删除mysql数据库中的数据。
首先,在Eggjs中使用egg-mysql插件,需要在config/config.default.js和config/plugin.js中进行相关配置:
// config/config.default.js exports.mysql = { // 单数据库信息配置 client: { host: 'localhost',port: '3306',user: 'root',password: 'root',database: 'test',},// 是否加载到 app 上,默认开启 app: true,// 是否加载到 agent 上,默认关闭 agent: false,}; // config/plugin.js exports.mysql = { enable: true,package: 'egg-mysql',};
然后,在Controller中引入mysql以及相关的Service:
// app/controller/user.js const Controller = require('egg').Controller; class UserController extends Controller { async deleteUser() { const { ctx,app } = this; const { id } = ctx.query; const mysql = app.mysql; const row = { id: Number(id),}; const result = await mysql.delete('user',row); ctx.body = result; } } module.exports = UserController;
在deleteUser方法中,首先获取了请求参数中的id,然后调用mysql.delete方法来删除id对应的数据。其中,'user'为表名,row为删除条件。
最后,需要在Route中配置deleteUser方法的路由:
// app/router.js module.exports = app => { const { router,controller } = app; router.get('/user/delete',controller.user.deleteUser); };
上述代码完成后,即可在浏览器中访问http://localhost:7001/user/delete?id=1来删除id为1的数据。当然,在实际开发中,可以将id作为参数传递进来,然后进行删除。
至此,本文介绍了如何使用egg-mysql插件中的delete方法来删除mysql数据库中的数据。使用时需要配置插件、引入mysql以及相关的Service,调用mysql.delete方法来进行删除操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。