当前位置:网站首页>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}));
});
边栏推荐
猜你喜欢
人工肌肉智能材料新突破
prometheus-tls加密
The terminal connection tools, rolling Xshell
Boot process and service control
The introduction of AI meta-learning into neuroscience, the medical effect is expected to improve accurately
Multithreading basics (multithreaded memory, security, communication, thread pools and blocking queues)
RAID磁盘阵列
UDP和TCP使用同一个端口,可行吗?
prometheus监控mysql
From catching up to surpassing, domestic software shows its talents
随机推荐
Install MySQL under Linux (centos7)
相机坐标系,世界坐标系,像素坐标系三者转换,以及OPENGLDEFocal Length和Opengl 的 Fov转换
阿里二面:Redis有几种集群方案?我答了4种
Test development engineer diary 002 - starting from 0 interface automation
debian 问题
Headline 2: there are several kinds of common SQL errors in MySQL usage?
The terminal connection tools, rolling Xshell
万能js时间日期格式转换
Test and Development Engineer Growth Diary 009 - Environment Pai Pai Station: Development Environment, Test Environment, Production Environment, UAT Environment, Simulation Environment
From catching up to surpassing, domestic software shows its talents
和AI一起玩儿剧本杀:居然比我还入戏
Swagger使用方式,告别postman
测试开发工程师成长日记001 - 敏捷测试、CI/CD/CT、DecOps的一些介绍
Multithreading basics (concept, create, interrupt)
Camera coordinate system, world coordinate system, pixel coordinate system conversion, and Fov conversion of OPENGLDEFocal Length and Opengl
矩阵的行列式的计算及其源码
matlab机器学习_01
RAID disk array
Polygon 3D(三维平面多边形)的法向量的计算(MeshLab默认的计算)
The CTO said I was not advised to use SELECT *, why is that?