当前位置: 首页 > 后端技术 > Node.js

nodejs+express+mssql对数据操作进行封装

时间:2023-04-03 15:42:45 Node.js

在网上看到一些nodejs连接sqlserver的教程,但是很少,而且很多都是错误的,尤其是操作数据库的语句。这里我整理了一下。搭建完整的nodejs后台,封装sqlserver的操作。nodejs和express的安装这里就不多说了。网上有教程,不懂的可以上网搜索。然后安装mssql,在终端进入你的项目文件夹,输入命令:npminstallmssql,稍等片刻,安装完成。这时候新建一个db.js(任意名字)开始封装数据操作。我一般新建一个和routes、views同级的文件夹,放一些public的js,比如分页功能包page.js等。让我们开始打包数据库。先放代码:/***sqlserverModel**/constmssql=require("mssql");constconf=require("../config.js");constpool=newmssql.ConnectionPool(conf)constpoolConnect=pool.connect()pool.on('error',err=>{console.log('error:',err)})/***自由查询*@paramsqlSQL语句,例如:'select*来自newswhereid=@id'*@paramparams参数,用于在sql中解释@*,例如:{id:id}*@paramcallBack回调函数*/letquerySql=asyncfunction(sql,params,callBack){尝试{让ps=newmssql.PreparedStatement(awaitpoolConnect);if(params!=""){for(letindexinparams){if(typeofparams[index]=="number"){ps.input(index,mssql.Int);}elseif(typeofparams[index]=="string"){ps.input(index,mssql.NVarChar);}}}ps.prepare(sql,function(err){if(err)console.log(err);ps.execute(params,function(err,记录集){callBack(err,记录集);ps.unprepare(function(err){if(err)console.log(err);});});});}catch(e){console.log(e)}};/***根据条件和要求查询指定表*@paramtableName数据库表名,例如:'news'*@paramtopNumber只查询前几条数据,可以为空,如果为空则表示查询所有*@paramwhereSql条件语句,例如:'whereid=@id'*@paramparams参数,用于解释sql中的@*,例如:{id:id}*@paramorderSql排序语句,例如:'orderbycreated_date'*@paramcallBack回调函数*/letselect=asyncfunction(tableName,topNumber,whereSql,params,orderSql,callBack){try{让ps=newmssql.PreparedStatement(awaitpoolConnect);letsql="select*from"+tableName+"";if(topNumber!=""){sql="selecttop("+topNumber+")*from"+tableName+"";}sql+=whereSql+"";if(params!=""){for(letindexinparams){if(typeofparams[index]=="number"){ps.input(index,mssql.Int);}elseif(typeofparams[index]=="string"){ps.input(index,mssql.NVarChar);}}}sql+=orderSql;控制台日志(sql);ps.prepare(sql,function(err){if(err)console.log(err);ps.execute(params,function(err,recordset){callBack(err,recordset);ps.unprepare(function(err){如果(错误)console.log(错误);});});});}catch(e){console.log(e)}};/***查询指定表的所有数据*@paramtableName数据库表名*@paramcallBack回调函数*/letselectAll=asyncfunction(tableName,callBack){尝试{让ps=newmssql.PreparedStatement(awaitpoolConnect);letsql="select*from"+tableName+"";附言。准备(SQL,函数化(错误){如果(错误)console.log(错误);ps.execute("",function(err,recordset){callBack(err,recordset);ps.unprepare(function(err){if(err)console.log(err);});});});}catch(e){console.log(e)}};/***向指定表添加字段*@paramaddObj对象要添加的字段,示例:{name:'name',age:20}*@paramtableName数据库表名*@paramcallBack回调函数*/letadd=asyncfunction(addObj,tableName,callBack){try{letps=newmssql.PreparedStatement(awaitpoolConnect);letsql="insertinto"+tableName+"(";if(addObj!=""){for(letindexinaddObj){if(typeofaddObj[index]=="number"){ps.input(index,mssql.Int);}elseif(typeofaddObj[index]=="string"){ps.input(index,mssql.NVarChar);}sql+=索引+",";}sql=sql.substring(0,sql.length-1)+")values(";for(letindexinaddObj){if(typeofaddObj[index]=="number"){sql+=addObj[index]+",";}elseif(typeofaddObj[index]=="string"){sql+="'"+addObj[index]+"'"+",";}}}sql=sql.substring(0,sql.length-1)+")SELECT@@IDENTITYid";//添加SELECT@@IDENTITYid以返回idps.prepare(sql,function(err){if(err)console.log(err);ps.execute(addObj,function(err,recordset){callBack(err,记录集);ps.unprepare(function(err){if(err)console.log(err);});});});}catch(e){console.log(e)}};/***更新指定表的数据*@paramupdateObj需要更新的对象字段,例如:{name:'name',age:20}*@paramwhereObj需要更新的条件,例如:{id:id}*@paramtableName数据库表名*@paramcallBack回调函数*/letupdate=asyncfunction(updateObj,whereObj,tableName,callBack){try{让ps=newmssql.PreparedStatement(awaitpoolConnect);letsql="update"+tableName+"set";if(updateObj!=""){for(letindexinupdateObj){if(typeofupdateObj[index]=="number"){ps.input(index,mssql.Int);sql+=index+"="+updateObj[index]+",";}elseif(typeofupdateObj[index]=="string"){ps.input(index,mssql.NVarChar);sql+=index+"="+"'"+updateObj[index]+"'"+",";}}}sql=sql.substring(0,sql.length-1)+"哪里";if(whereObj!=""){for(letindexinwhereObj){if(typeofwhereObj[index]=="number"){ps.input(index,mssql.Int);sql+=index+"="+whereObj[index]+"and";}elseif(typeofwhereObj[index]=="string"){ps.input(index,mssql.NVarChar);sql+=index+"="+"'"+whereObj[index]+"'"+"and";}}}sql=sql.substring(0,sql.length-5);ps.prepare(sql,function(err){if(err)console.log(err);ps.execute(updateObj,function(err,recordset){callBack(err,recordset);ps.unprepare(function(err){如果(错误)console.log(错误);});});});}catch(e){console.log(e)}};/***删除指定表字段*@paramwhereSql为删除字段的条件语句,例如:'whereid=@id'*@paramparamsparameter,在sql中用来解释@*,例如:{id:id}*@paramtableName数据库表名*@paramcallBack回调函数*/letdel=asyncfunction(whereSql,params,tableName,callBack){try{让ps=newmssql.PreparedStatement(awaitpoolConnect);letsql="deletefrom"+tableName+"";if(params!=""){for(letindexinparams){if(typeofparams[index]=="number"){ps.input(index,mssql.Int);}elseif(typeofparams[index]=="string"){ps.input(index,mssql.NVarChar);}}}sql+=whereSql;ps.prepare(sql,function(err){if(err)console.log(err);ps.execute(params,function(err,recordset){callBack(err,recordset);ps.unprepare(function(err){如果(错误)console.log(错误);});});});}catch(e){console.log(e)}};exports.config=conf;exports.del=del;exports.select=select;exports.update=update;exports.querySql=querySql;exports.selectAll=selectAll;exports.add=add;这里还需要一个config.js:letapp={user:'sa',password:'',server:'localhost',database:'database',port:1433,options:{encrypt:true//如果使用这个你在WindowsAzureenableArithAbort:true,},pool:{min:0,max:10,idleTimeoutMillis:3000}};module.exports=app;这样就完成了包。网上很多教程都是用mssql.Connection(),但是你会发现有的会报错没有这个功能,有的改成mssql.connect(),虽然可以,但是会报错第二次使用数据库时。大致就是你的数据库已经连上了,需要关闭才能再连上。mssql.ConnectionPool()不存在此类问题。下面是使用,以index.js为例:constexpress=require('express');constdb=require('../utils/db.js');constmoment=require('moment');constrouter=express.Router();/*获取主页。*/router.get('/',function(req,res,next){db.selectAll('news',function(err,result){//查询所有新闻表数据res.render('newsList',{results:records.recordset,moment:moment});});});router.get('/delete/:id',function(req,res,next){//删除news表对应的数据一个idvarid=req.params.id;db.del("whereid=@id",{id:id},"news",function(err,result){res.redirect('back');//返回上一页});});router.post('/update/:id',function(req,res,next){//更新id对应的一个news表的数据varid=req.params.id;varcontent=req.body.content;db.update({content:content},{id:id},"news",function(err,result){res.redirect('back');});});module.exports=路由器;这样就实现了nodejs和mssql的使用