当前位置:网站首页>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}));
});
边栏推荐
- Process and Scheduled Task Management
- PXE efficient mass network capacity
- MongoDB - query
- 大飞机C919都用了哪些新材料?
- When does MySQL use table locks and when does it use row locks?
- STL源码剖析:class template explicit specialization代码测试和理解
- Table with tens of millions of data, how to query the fastest?
- Pioneer in Distributed Systems - Leslie Lambert
- Test Development Engineer Growth Diary 003 - Interface Automation Framework Construction
- Local Implicit Grid Representations for 3D Scenes详解
猜你喜欢

New breakthrough in artificial muscle smart materials

大飞机C919都用了哪些新材料?

The Geometric Meaning of Vector Cross Product and the Calculation of Modulus

New material under the plastic restriction order - polylactic acid (PLA)

When does MySQL use table locks and when does it use row locks?

Test development engineer growth diary 016 - those things about the test

The Society of Mind - Marvin Minsky

空间顶点到平面的距离计算的证明及其源码

MySql connecting to the server remotely

Dachang's annual salary of 50w+ recruits test engineers with test platform development capabilities
随机推荐
The Society of Mind - Marvin Minsky
The calculation of the determinant of the matrix and its source code
STL源码剖析:临时对象的代码测试和理解
Proftpd配置文件
Test Development Engineer Growth Diary 015 - Top 20 Test Interview Questions
Test Development Engineer Growth Diary 008 - Talking About Some Bugs/Use Case Management Platform/Collaboration Platform
搭建vsftpd服务并实现本地用户访问
Multithreading basics (multithreaded memory, security, communication, thread pools and blocking queues)
RAID disk array
mpich安装
软件测试_01
LVM和磁盘配额
Rodrigues:旋转矩阵的向量表达
从追赶到超越,国产软件大显身手
LVM and disk quotas
The concept and testing method of black box testing
The calculation proof of the intersection of the space line and the plane and its source code
你被MySQL 中的反斜杠 \\坑过吗?
The Geometric Meaning of Vector Cross Product and the Calculation of Modulus
matlab机器学习_01