当前位置:网站首页>node.js中实现对数据库的链式操作
node.js中实现对数据库的链式操作
2022-07-30 05:50:00 【HW-Header】
在平时的业务需求中,总是经常与数据库打交道,但书写SQL语句有时候是真的很头大。业务简单那还好,但遇到情况比较复杂时,也许就是一个字符串的拼接问题,却很难找到原因。
为了解决SQL语句的书写问题,我想到了其他编程语言中的数据库链式操作,很好地简化了对数据库的操作复杂度,但遗憾的是node.js中没有相应的第三方包,于是我们自己实现。
首先我们需要先搞清楚链式操作的原理:链式操作无非就是几个方法一个接一个地调用。就比如db.from().fields().where(),db是一个对象,调用了from方法,然后调用了fileds方法,最后调用where方法。问题来了,我们都知道,调用一个方法之后,一般都是得到一个结果,而结果如何能再继续调用下一个方法?能调用方法的前提,肯定本身就是一个对象,那我们在调用方法之后返回一个对象,而且这个对象还必须为当前对象本身this(我们需要把form、fields、where等方法封装到db对象中,因此就只有db对象才有这些业务方法,那为了链式操作,就只能前一个方法返回this,才能继续调用下一个方法)。
完整代码如下,封装的方法不是很多,不过原理都是一样的,有兴趣的读者可自行研究:
自定义封装数据库操作的模块
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
port : '3308',
database : 'class'
});
connection.connect();
class ValidationError extends Error {
constructor(message) {
super(message); // (1)
this.name = "SqlError"; // (2)
}
}
module.exports.db = {
// 导出一个对象,供其他模块使用
from: function(table){
if(table === undefined)
throw new ValidationError('数据表未指定');
else{
this.table = table;
return this;
}
},
fileds: function(fd){
if(fd === undefined){
this.fd = '*';
return this;
}
else{
this.fd = fd;
return this;
}
},
where: function(wh){
this.wh = wh;
return this;
},
query: function(callback){
if(callback === undefined)
throw new ValidationError('未指定回调函数')
else{
this.fd===undefined?this.fd='*':'';
if(this.wh === undefined){
sql = `select ${
this.fd} from ${
this.table}`;
QuerySql(sql, callback);
}
else{
sql = `select ${
this.fd} from ${
this.table} where ${
this.wh}`;
QuerySql(sql, callback);
}
}
},
}
function QuerySql(sql, callback){
// 根据sql语句查询数据库
connection.query(sql, function(error, results, fields){
if (error) throw error;
callback(results); // 查询结果才调用回调返回数据
});
}
其他模块中如何调用数据库链式操作方法?
mysqlCon.db.from('student').fields('id,name').where('age < 20').query(function(data){
res.end(template('./index.html', {
data: data}));
});
边栏推荐
- 限塑令下的新材料——聚乳酸(PLA)
- 大飞机C919都用了哪些新材料?
- Test the basics 02
- Is it possible to use the same port for UDP and TCP?
- 预测人们对你的第一印象,“AI颜狗”的诞生
- 识别“数据陷阱”,发现数据的可疑之处
- Install MySQL under Linux (centos7)
- Test Development Engineer Growth Diary 018 - Record of Required Questions for Test Interview (Continuous Update)
- The calculation proof of the intersection of the space line and the plane and its source code
- numpy 多维数组ndarray的详解
猜你喜欢

引导过程与服务控制

Let the "label" content in Baidu map generator expand--solution

Install MySQL under Linux (centos7)

相机坐标系,世界坐标系,像素坐标系三者转换,以及OPENGLDEFocal Length和Opengl 的 Fov转换

测试开发工程师成长日记001 - 敏捷测试、CI/CD/CT、DecOps的一些介绍

export , export default, import complete usage

B站崩了,如果是你是那晚负责的开发人员你会怎么做?

MongoDB-CUD without R

The calculation and source code of the straight line intersecting the space plane

STL源码剖析:class template explicit specialization代码测试和理解
随机推荐
Redis 如何实现防止超卖和库存扣减操作?
人工肌肉智能材料新突破
不会吧,Log4j 漏洞还没有完全修复?
千万级数据量的表,怎样最快速度查询?
Linx常见目录&文件管理命令&VI编辑器使用 介绍
Ali two sides: List several tips for Api interface optimization
AI元学习引入神经科学,医疗效果有望精准提升
How to understand plucker coordinates (geometric understanding)
阿里一面:多线程顺序运行有多少种方法?
Linx common directory & file management commands & VI editor usage introduction
向量的导数运算和向量叉乘以及点乘的导数运算
The calculation and source code of the straight line intersecting the space plane
@Bean 与 @Component 用在同一个类上,会怎样?
DHCP principle and configuration
SE_01
这个终端连接工具,碾压Xshell
DNS域名解析服务
When does MySQL use table locks and when does it use row locks?
新人误删数据,组长巧用MySQL主从复制延迟挽回损失
Test Development Engineer Growth Diary 007 - Bug Priority Definition and Filling Specifications