在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. P2894 [USACO08FEB]酒店Hotel 线段树

    题目大意 多次操作 查询并修改区间内长度==len的第一次出现位置 修改区间,变为空 思路 类似于求区间最大子段和(应该是这个吧,反正我没做过) 维护区间rt的 从l开始向右的最长长度 从r开始向左的 ...

  2. Java名称由来

              2000年度的JavaOne国际会议大厅热闹非凡,一阵阵浓郁的咖啡味儿香气扑鼻.从世界各地汇集到旧金山参加会议的Java精英们兴奋异常,排着长队,等待得到一杯由Java语言控制的咖 ...

  3. UVa 11039 设计建筑物

    https://vjudge.net/problem/UVA-11039 题意: 有n个绝对值各不相同的非0整数,选出尽量多的数,排成一个序列,使得正负号交替且绝对值递增. 思路:正数存一个数组,负数 ...

  4. UVa 12563 劲歌金曲(0-1背包)

    https://vjudge.net/problem/UVA-12563 题意: 在一定的时间内连续唱歌,最后一首唱11分钟18秒的劲歌金曲,问最多能长多长时间. 思路: 0-1背包问题,背包容量为t ...

  5. C# Int转Enum

    Int-->Enum (1)可以强制转换将整型转换成枚举类型. 例如:Colors color = (Colors)2 ,那么color即为Colors.Blue (2)利用Enum的静态方法T ...

  6. linux——压缩解压命令学习简单笔记

    一: 命令名称:gzip 命令英文原意:GNU zip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip 选项 [文件] 功能描述:压缩文件 压缩后文件格式:.gz 1:只能压缩文 ...

  7. Codeforces Beta Round #16 div 2 C.Monitor最大公约数

    C. Monitor time limit per test 0.5 second memory limit per test 64 megabytes input standard input ou ...

  8. codevs 1081 线段树练习 2 线段树

    题目描述 Description 给你N个数,有两种操作 1:给区间[a,b]的所有数都增加X 2:询问第i个数是什么? 输入描述 Input Description 第一行一个正整数n,接下来n行n ...

  9. A start job is running for Raise network interface(5min 13s )问题解决方法

    命令:sudo vim /etc/systemd/system/network-online.target.wants/networking.service将里面的TimeoutStartSec=5m ...

  10. MVC修改视图的默认路径

    概述:之前MVC5和之前的版本中,我们要想对View文件的路径进行控制的话,则必须要对IViewEngine接口的FindPartialView或FindView方法进行重写,所有的视图引擎都继承于该 ...