在nodejs中,mssql模块支持sqlserver数据库操作。今天将mssql模块的某些功能封装为一个类,方便以后调用。封装的功能有执行存储过程,执行查询语句操作等。如果本篇文章对大家有帮助,那就再好不过了!

要使用mssql模块,请先用npm加载到项目中。加载过程:打开cmd命令框,定位到项目的根目录下,输入npm install mssql --save ,然后按回车键就OK!

封装的代码如下:

//导入mssql模块
var mssql=require("mssql"); var sql={}; //连接参数配置
var config={
user:"sa",
password:"wsjun123456",
server:"localhost", // You can use 'localhost\\instance' to connect to named instance
database:"mydb",
stream:false, // You can enable streaming globally
/*option:{
encrypt:true //Use this if you're on Windows Azure
},*/
pool:{
min:,
idleTimeoutMillis:
}
}; sql.sqlserver=mssql; //sql参数的类型
sql.direction={
//输入参数
Input:"input",
//输出参数
Output:"output",
//返回参数
Return:"return"
}; /**
* 初始化连接参数
* @param {string} user 用户名
* @param {string} password 密码
* @param {string} server 服务器地址
* @param {string} database 数据库名称
*/
sql.initConfig=function(user,password,server,database){
config={
user:user,
password:password,
server:server, // You can use 'localhost\\instance' to connect to named instance
database:database,
stream:false,
/*option:{
encrypt:true //Use this if you're on Windows Azure
},*/
pool:{
min:,
idleTimeoutMillis:
}
};
} /**
* 执行存储过程
* @param {string} procedure 存储过程名称
* @param {JSON} params 存储过程参数
* params的定义格式如:
var params={
//ID是存储过程的第一个参数,要去掉@符号
ID:{
//sqlType是该ID参数在sqlserver中的类型
sqlType:sql.sqlserver.Int,
//direction是表明ID参数是输入还是输出(output)参数
direction:sql.direction.Input,
//该ID参数的值
inputValue:1
},
//Name是存储过程的第二个参数,要去掉@符号
Name:{
sqlType:sqlHelper.sqlserver.Int,
direction:sqlHelper.direction.Output,
outputValue:null
}
};
* @param {function} func 回调函数 共有四个参数 error:错误信息 recordsets:查询的表结果 returnValue:存储过程的返回值 affected:影响的行数
*/
sql.execute=function(procedure,params,func){
try {
var connection = new mssql.Connection(config, function (error) {
if(error)
func(error);
else {
var request = new mssql.Request(connection);
//request.verbose=true;
if (params != null) {
for (var index in params) {
if (params[index].direction == sql.direction.Output) {
request.output(index, params[index].sqlType);
}
else {
request.input(index, params[index].sqlType, params[index].inputValue);
}
}
}
request.execute(procedure, function (error, recordsets, returnValue, affected) {
if (error)
func(error);
else {
for (var index in params) {
if (params[index].direction == sql.direction.Output) {
params[index].outputValue = request.parameters[index].value;
}
}
func(error, recordsets, returnValue, affected);
}
});
}
}); connection.on("error", func); }catch(e){
func(e);
}
}; /**
* 执行sql文本(带params参数)
* @param {string} sqltext 执行的sql语句
* @param {JSON} params sql语句中的参数
* @param {function} func 回调函数 共有三个参数 error:错误消息 recordsets:查询的结果 affected:影响的行数
*/
sql.queryWithParams=function(sqltext,params,func){
try {
var connection = new mssql.Connection(config, function (err) {
if(err)
func(err);
else {
var request = new mssql.Request(connection);
request.multiple=true; if(params){
for(var index in params){
request.input(index,params[index].sqlType,params[index].inputValue);
}
} request.query(sqltext, func);
}
});
connection.on("error",func);
}catch(e){
func(e);
}
}; /**
* 执行sql文本
* @param {string} sqltext 执行的sql语句
* @param {function} func 回调函数 共有三个参数 error:错误消息 recordsets:查询的结果 affected:影响的行数
*/
sql.query=function(sqltext,func){
sql.queryWithParams(sqltext,null,func);
}; /**
* 执行大批量数据的插入
* @param {sqlserver.Table} table 需要插入的数据表
* 数据表的定义如下:
var table=new sql.sqlserver.Table('UserInfoTest');
table.create=true;
table.columns.add('name',sqlHelper.sqlserver.NVarChar(50),{nullable:true});
table.columns.add('pwd',sqlHelper.sqlserver.VarChar(200),{nullable:true});
table.rows.add('张1','jjasdfienf');
table.rows.add('张2','jjasdfienf');
table.rows.add('张3','jjasdfienf');
* @param {function} func 回调函数 共有两个参数 error:错误信息 rowcount:插入数据的行数
*/
sql.bulkInsert=function(table,func){
try{
if(table){
var connection=new mssql.Connection(config,function(err){
if(err) func(err)
else{
var request=new mssql.Request(connection);
request.bulk(table,func);
}
});
connection.on("error",func);
}
else
func(new ReferenceError('table parameter undefined!'));
}catch (e){
func(e);
}
}; /**
* 如果需要处理大批量的数据行,通常应该使用流
* @param {string} sqltext 需要执行的sql文本
* @param {JSON} params 输入参数
* @param {JSON} func 表示一个回调函数的JSON对象,如下所示:
* {
error:function(err){
console.log(err);
},
columns:function(columns){
console.log(columns);
},
row:function(row){
console.log(row);
},
done:function(affected){
console.log(affected);
}
*/
sql.queryViaStreamWithParams=function(sqltext,params,func){
try{
config.stream=true; mssql.connect(config,function(err){
if(err)
func.error(err);
else{
var request=new mssql.Request();
request.stream=true;// You can set streaming differently for each request
if(params){
for(var index in params){
request.input(index,params[index].sqlType,params[index].inputValue);
}
} request.query(sqltext); request.on('recordset',function(columns){
//columns是一个JSON对象,表示 返回数据表的整个结构,包括每个字段名称以及每个字段的相关属性
//如下所示
/*
{ id:
{ index: 0,
name: 'id',
length: undefined,
type: [sql.Int],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: true,
readOnly: true },
name:
{ index: 1,
name: 'name',
length: 100,
type: [sql.NVarChar],
scale: undefined,
precision: undefined,
nullable: true,
caseSensitive: false,
identity: false,
readOnly: false },
Pwd:
{ index: 2,
name: 'Pwd',
length: 200,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: true,
caseSensitive: false,
identity: false,
readOnly: false } }
*/
func.columns(columns);
}); request.on('row', function(row) {
//row是一个JSON对象,表示 每一行的数据,包括字段名和字段值
//如 { id: 1004, name: 'jsw', Pwd: '12345678' }
//如果行数较多,会多次进入该方法,每次只返回一行
func.row(row);
}); request.on('error', function(err) {
//err是一个JSON对象,表示 错误信息
//如下所示:
/*
{ [RequestError: Incorrect syntax near the keyword 'from'.]
name: 'RequestError',
message: 'Incorrect syntax near the keyword \'from\'.',
code: 'EREQUEST',
number: 156,
lineNumber: 1,
state: 1,
class: 15,
serverName: '06-PC',
procName: '' }
*/
func.error(err);
}); request.on('done', function(affected) {
//affected是一个数值,表示 影响的行数
//如 0
//该方法是最后一个执行
func.done(affected);
});
}
}); mssql.on('error',func.error);
}catch(e){
func.error(e);
}finally{
config.stream=false;
}
}; /**
* 如果需要处理大批量的数据行,通常应该使用流
* @param {string} sqltext 需要执行的sql文本
* @param {JSON} func 表示一个回调函数的JSON对象,如下所示:
* {
error:function(err){
console.log(err);
},
columns:function(columns){
console.log(columns);
},
row:function(row){
console.log(row);
},
done:function(affected){
console.log(affected);
}
*/
sql.queryViaStream=function(sqltext,func){
sql.queryViaStreamWithParams(sqltext,null,func);
}; module.exports=sql;

本篇文章是根据https://www.npmjs.com/package/mssql来写作的,不足之处,请勿见怪,本人新手!

Nodejs之mssql模块的封装的更多相关文章

  1. nodejs:连接数据库SqlServer,mssql模块

    现在的数据库越来越多,如mgdb,我比较常用的是mysql,但有一天做项目需要连接SqlServer,就去找了个方法.找了很多无非就mssql模块和node-sqlserver模块,但node-sql ...

  2. nodejs利用http模块实现银行卡所属银行查询和骚扰电话验证

    http模块内部封装了http服务器和客户端,因此Node.js不需要借助Apache.IIS.Nginx.Tomcat等传统HTTP服务器,就可以构建http服务器,亦可以用来做一些爬虫.下面简单介 ...

  3. Nodejs的http模块

    一.http服务器    我们知道传统的HTTP服务器是由Aphche.Nginx.IIS之类的软件来搭建的,但是Nodejs并不需要,Nodejs提供了http模块,自身就可以用来构建服务器,例如: ...

  4. nodeJS里面的模块

    this 打开cmd,执行如下命令 nodeconsole.log(this); 输出如上信息,表示this是global,每个电脑的配置信息不一样的话,可能会有所差别的. 然后新建一个文件,写下如下 ...

  5. Nodejs中关于模块的总结

    关于Nodejs中的模块 概念 Nodejs在ECMAScript的基础上扩展并封装了许多高级特性,如文件访问.网络访问等,使得Nodejs成为一个很好的Web开发平台.基于Nodejs这个平台将We ...

  6. 如何为编程爱好者设计一款好玩的智能硬件(九)——LCD1602点阵字符型液晶显示模块驱动封装(下)

    六.温湿度传感器DHT11驱动封装(下):如何为编程爱好者设计一款好玩的智能硬件(六)——初尝试·把温湿度给收集了(下)! 七.点阵字符型液晶显示模块LCD1602驱动封装(上):如何为编程爱好者设计 ...

  7. 如何为编程爱好者设计一款好玩的智能硬件(八)——LCD1602点阵字符型液晶显示模块驱动封装(中)

    六.温湿度传感器DHT11驱动封装(下):如何为编程爱好者设计一款好玩的智能硬件(六)——初尝试·把温湿度给收集了(下)! 七.点阵字符型液晶显示模块LCD1602驱动封装(上):如何为编程爱好者设计 ...

  8. 关于Nodejs的多进程模块Cluster

    关于Nodejs的多进程模块Cluster   前述 我们都知道nodejs最大的特点就是单进程.无阻塞运行,并且是异步事件驱动的.Nodejs的这些特性能够很好的解决一些问题,例如在服务器开发中,并 ...

  9. Nodejs中cluster模块的多进程共享数据问题

    Nodejs中cluster模块的多进程共享数据问题 前述 nodejs在v0.6.x之后增加了一个模块cluster用于实现多进程,利用child_process模块来创建和管理进程,增加程序在多核 ...

随机推荐

  1. assert函数用法总结【转】

    本文转载自:http://blog.csdn.net/u014082714/article/details/45190505 assert宏的原型定义在<assert.h>中,其作用是如果 ...

  2. ReadResolve方法与序列化

    使用枚举实现的单例模式,不但可以防止利用反射强行构建单例对象,而且可以在枚举类对象被反序列化的时候,保证反序列的返回结果是同一对象. 对于其他方式实现的单例模式,如果既想要做到可序列化,又想要反序列化 ...

  3. JavaScript 题目

    1. ],b=a; b[]=; console.log(a+b); a=[], b=a, b=[]; console.log(a+b); 2.快速排序法 var quickSort = functio ...

  4. 【第二十一章】 springboot + 定时任务

    1.application.properties #cron job.everysecond.cron=0/1 * * * * * job.everytensecond.cron=0/10 * * * ...

  5. BZOJ3296: [USACO2011 Open] Learning Languages 并查集

    Description 农夫约翰的N(2 <= N<=10,000)头奶牛,编号为1.. N,一共会流利地使用M(1<= M <=30,000)种语言,编号从1  .. M., ...

  6. HDU 6162 Ch's gift(树链剖分+线段树)

    题意: 已知树上的每个节点的值和节点之间的关系建成了一棵树,现在查询节点u到节点v的最短路径上的节点值在l到r之间的节点值的和. 思路: 用树链剖分将树映射到线段树上,线段树上维护3个值,max,mi ...

  7. 华中农业大学预赛 B Handing Out Candies 余数的和

    Problem B: Handing Out Candies Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 258  Solved: 19[Submit ...

  8. 安装 mysql5.7.2 (Ubuntu 16.04 desktop amd64)

    1.下载mysql deb https://dev.mysql.com/downloads/mysql/ #移动到/usr/local/src/目录,解压 sudo mv mysql-server_5 ...

  9. python将xml转换成json数据

    # -*- coding: utf-8 -*- import requests import xmltodict import json def get_response(request_url): ...

  10. [原][osg][osgEarth]关于在OE中使用物理引擎的调研

    关于物理引擎旋转的一些整理 参考文档 http://blog.wolfire.com/2010/03/Comparing-ODE-and-Bullet 介绍ODE和bullet的利弊 http://s ...