Express调用mssql驱动公共类dbHelper

直接上代码:

/**
* Created by chaozhou on 2015/9/18.
*/
var mssql = require('mssql');
var user = "sa",
password = "sa",
server = "192.168.20.132",
database = "ggcms";

/**
* 默认config对象
* @type {{user: string, password: string, server: string, database: string, options: {encrypt: boolean}, pool: {min: number, idleTimeoutMillis: number}}}
*/
var config = {
user: user,
password: password,
server: server, // You can use 'localhost\\instance' to connect to named instance
database: database,
options: {
encrypt: true // Use this if you're on Windows Azure
},
pool: {
min: 0,
idleTimeoutMillis: 3000
}
};

/**
* 初始化config
* @param user
* @param password
* @param server
* @param database
*/
var 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,
options: {
encrypt: true // Use this if you're on Windows Azure
},
pool: {
min: 0,
idleTimeoutMillis: 3000
}
}
};

/**
* 恢复默认config
*/
var restoreDefaults = function () {
config = {
user: user,
password: password,
server: server, // You can use 'localhost\\instance' to connect to named instance
database: database,
options: {
encrypt: true // Use this if you're on Windows Azure
},
pool: {
min: 0,
idleTimeoutMillis: 3000
}
};
};

/**
* 执行原生Sql
* @param sql
* @params 参数对象(可为空,为空表示不加参数)
* @param callBack(err,recordset)
*/
var querySql = function (sql, params, callBack) {
var connection = new mssql.Connection(config, function (err) {
var ps = new mssql.PreparedStatement(connection);
if (params != "") {
for (var index in params) {
if (typeof params[index] == "number") {
ps.input(index, mssql.Int);
} else if (typeof params[index] == "string") {
ps.input(index, mssql.NVarChar);
}
}
}
console.log("sql:" + sql);
ps.prepare(sql, function (err) {
if (err)
console.log(err);
ps.execute(params, function (err, recordset) {
callBack(err, recordset);
ps.unprepare(function (err) {
if (err)
console.log(err);
});
});
});
});
restoreDefaults();
};

/**
* 带参数查询
* @param tableName 表名
* @param topNumber 前topNumber条
* @param whereSql whereSql
* @param params 查询参数对象(可为"",为""表示不加任何参数,如果此项为"",则whereSql必须也为"")
* @param orderSql 排序Sql(可为"",为""表示不排序)
* @param callBack
*/
var select = function (tableName, topNumber, whereSql, params, orderSql, callBack) {
var connection = new mssql.Connection(config, function (err) {
var ps = new mssql.PreparedStatement(connection);
var sql = "select * from " + tableName + " ";
if (topNumber != "") {
sql = "select top(" + topNumber + ") * from " + tableName + " ";
}
sql += whereSql + " ";
if (params != "") {
for (var index in params) {
if (typeof params[index] == "number") {
ps.input(index, mssql.Int);
} else if (typeof params[index] == "string") {
ps.input(index, mssql.NVarChar);
}
}
}
sql += orderSql;
console.log(sql);
ps.prepare(sql, function (err) {
if (err)
console.log(err);
ps.execute(params, function (err, recordset) {
callBack(err, recordset);
ps.unprepare(function (err) {
if (err)
console.log(err);
});
});
});
});
restoreDefaults();
};

//select("dbo.userInfo",3,"where id = @id",{id:1},"order by id",function(err,recordset){
// console.log(recordset);
//});

/**
* 查询所有
* @param tableName
* @param callBack
*/
var selectAll = function (tableName, callBack) {
var connection = new mssql.Connection(config, function (err) {
var ps = new mssql.PreparedStatement(connection);
var sql = "select * from " + tableName + " ";
console.log("sql:" + sql);
ps.prepare(sql, function (err) {
if (err)
console.log(err);
ps.execute("", function (err, recordset) {
callBack(err, recordset);
ps.unprepare(function (err) {
if (err)
console.log(err);
});
});
});
});
restoreDefaults();
};

//selectAll("dbo.userTable",function(err,recordset){
// console.log(recordset);
//});

/**
* 添加
* @param addObj 添加对象(必填)
* @param tableName 表名
* @param callBack(err,recordset)
*/
var add = function(addObj,tableName,callBack){ //{id:3,userName:'admin'...} insert into dbo.tags(id,name) values(@id,@name)
var connection = new mssql.Connection(config, function (err) {
var ps = new mssql.PreparedStatement(connection);
var sql = "insert into " + tableName + "(";
if (addObj != "") {
for (var index in addObj) {
if (typeof addObj[index] == "number") {
ps.input(index, mssql.Int);
} else if (typeof addObj[index] == "string") {
ps.input(index, mssql.NVarChar);
} else if (typeof addObj[index] == "object") {
ps.input(index, mssql.DateTime);
}
sql += index + ",";
}
sql = sql.substr(0, sql.length - 1) + ")values(";
for (var index in addObj) {
sql = sql + "@" + index + ",";
}
}
sql = sql.substr(0, sql.length - 1) + ")";
console.log(sql);
ps.prepare(sql, function (err) {
if (err)
console.log(err);
ps.execute(addObj, function (err, recordset) {
callBack(err, recordset);
ps.unprepare(function (err) {
if (err)
console.log(err);
});
});
});
});
restoreDefaults();
};

//add({"updateTime":new Date(),name:'awdaw,3awdwa,3434'},"dbo.template",function(err,recordset){
// console.log(recordset);
//});

//var add = function (addObj, tableName, callBack) {
// var connection = new mssql.Connection(config, function (err) {
// var ps = new mssql.PreparedStatement(connection);
// var sql = "insert into " + tableName + "(";
// if (addObj != "") {
// for (var index in addObj) {
// if (typeof addObj[index] == "number") {
// ps.input(index, mssql.Int);
// } else if (typeof addObj[index] == "string") {
// ps.input(index, mssql.NVarChar);
// }
// sql += index + ",";
// }
// sql = sql.substring(0, sql.length - 1) + ") values(";
// for (var index in addObj) {
// if (typeof addObj[index] == "number") {
// sql += addObj[index] + ",";
// } else if (typeof addObj[index] == "string") {
// sql += "'" + addObj[index] + "'" + ",";
// }
// }
// }
// sql = sql.substring(0, sql.length - 1) + ")";
// console.log("sql:" + sql);
// ps.prepare(sql, function (err) {
// if (err)
// console.log(err);
// ps.execute(addObj, function (err, recordset) {
// callBack(err, recordset);
// ps.unprepare(function (err) { //回收连接至连接池
// if (err)
// console.log(err);
// });
// });
// });
// });
// restoreDefaults();
//};



/**
* 修改
* @param updateObj 修改内容(必填)
* @param whereObj 修改对象(必填)
* @param tableName 表名
* @param callBack(err,recordset)
*/
var update = function(updateObj, whereObj, tableName, callBack){
var connection = new mssql.Connection(config, function (err) {
var ps = new mssql.PreparedStatement(connection);
var sql = "update " + tableName + " set ";
if (updateObj != "") {
for (var index in updateObj) {
if (typeof updateObj[index] == "number") {
ps.input(index, mssql.Int);
} else if (typeof updateObj[index] == "string") {
ps.input(index, mssql.NVarChar);
} else if (typeof updateObj[index] == "object") {
ps.input(index, mssql.DateTime);
}
sql += index + "=@" + index + ",";
}
sql = sql.substr(0, sql.length - 1) + " where ";
}
if (whereObj != "") {
for (var index in whereObj) {
if (typeof whereObj[index] == "number") {
ps.input(index, mssql.Int);
} else if (typeof whereObj[index] == "string") {
ps.input(index, mssql.NVarChar);
} else if (typeof whereObj[index] == "object") {
ps.input(index, mssql.DateTime);
}
sql += index + "=@" + index + ",";
}
}
sql = sql.substr(0, sql.length - 1);
var whereStr = JSON.stringify(whereObj);
var updateStr = JSON.stringify(updateObj);
whereObj = JSON.parse(updateStr.substr(0,updateStr.length -1) + "," + whereStr.substr(1,whereStr.length));
console.log(sql);
ps.prepare(sql, function (err) {
if (err)
console.log(err);
ps.execute(whereObj, function (err, recordset) {
callBack(err, recordset);
ps.unprepare(function (err) {
if (err)
console.log(err);
});
});
});
});
restoreDefaults();
};

//update({name:"awdawd",context:'awdaw33434',updateTime:'2015-09-25'},{id:2},"dbo.template",function(err,recordset){
// console.log(recordset);
//});

//var update = function (updateObj, whereObj, tableName, callBack) {
// var connection = new mssql.Connection(config, function (err) {
// var ps = new mssql.PreparedStatement(connection);
// var sql = "update " + tableName + " set "; //update userTable set userName = 'admin',loginTimes = 12,password = 'admin'
// if (updateObj != "") {
// for (var index in updateObj) {
// if (typeof updateObj[index] == "number") {
// ps.input(index, mssql.Int);
// sql += index + "=" + updateObj[index] + ",";
// } else if (typeof updateObj[index] == "string") {
// ps.input(index, mssql.NVarChar);
// sql += index + "=" + "'" + updateObj[index] + "'" + ",";
// }
// }
// }
// sql = sql.substring(0, sql.length - 1) + " where ";
// if (whereObj != "") {
// for (var index in whereObj) {
// if (typeof whereObj[index] == "number") {
// ps.input(index, mssql.Int);
// sql += index + "=" + whereObj[index] + " and ";
// } else if (typeof whereObj[index] == "string") {
// ps.input(index, mssql.NVarChar);
// sql += index + "=" + "'" + whereObj[index] + "'" + " and ";
// }
// }
// }
// sql = sql.substring(0, sql.length - 5);
// console.log("sql:" + sql);
// ps.prepare(sql, function (err) {
// if (err)
// console.log(err);
// ps.execute(updateObj, function (err, recordset) {
// callBack(err, recordset);
// ps.unprepare(function (err) { //回收连接至连接池
// if (err)
// console.log(err);
// });
// });
// });
// });
// restoreDefaults();
//};



/**
* 删除
* @param deleteObj 删除对象
* @param tableName 表名
* @param callBack(err,recordset)
*/
var del = function (whereSql, params, tableName, callBack) {
var connection = new mssql.Connection(config, function (err) {
var ps = new mssql.PreparedStatement(connection);
var sql = "delete from " + tableName + " ";
if (params != "") {
for (var index in params) {
if (typeof params[index] == "number") {
ps.input(index, mssql.Int);
} else if (typeof params[index] == "string") {
ps.input(index, mssql.NVarChar);
}
}
}
sql += whereSql;
console.log("sql:" + sql);
ps.prepare(sql, function (err) {
if (err)
console.log(err);
ps.execute(params, function (err, recordset) {
callBack(err, recordset);
ps.unprepare(function (err) { //回收连接至连接池
if (err)
console.log(err);
});
});
});
});
restoreDefaults();
};

//del("where id = @id",{id:16},"dbo.userTable",function(err,recordset){
// console.log(recordset);
//});

exports.initConfig = initConfig;
exports.config = config;
exports.del = del;
exports.select = select;
exports.update = update;
exports.querySql = querySql;
exports.restoreDefaults = restoreDefaults;
exports.selectAll = selectAll;
exports.add = add;

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/547331.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

怎么修改RO服务器版本,谁知道build.prop的系统版本号怎么改

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼# begin build properties# autogenerated by buildinfo.shro.build.idJDQ39ro.build.display.idJDQ39ro.build.version.incrementalV1.11ro.build.version.sdk17ro.build.version.codenameRELro.build.version.release4.2.2ro.bui…

清理vs工程文件(python2.7)

本文记录了两种方法,用于对vs目录的清理工作,这两种方法都是用python2.7实现的,一个是基于文件的扩展名,一个是基于文件的大小: 基于文件大小的清理脚本: #-*- coding:utf-8 -*- import os import string d…

Python如何忽略warning的输出

有时候运行代码时会有很多warning输出,如提醒新版本之类的,如果不想这些乱糟糟的输出可以这样: import warningswarnings.filterwarnings(ignore) 命令行下则可以: python -W ignore file.py 这样就可以避免warnings的输出了&…

nodejs常用组件

mssql 用途:连接SqlServer数据库 node-excel-export 用途:导出excel表格 nodegrass 用途:模拟用户进行get/post请求,下载文件等 uuid 用途:生成全球唯一标识的. 官网:https://npm.taobao.org/package/…

手机投屏时电视显示服务器有问题,小屏变大屏,手机投屏这几招你学废了么?...

马上七夕了,又恰逢周末不想去电影院凑热闹的人可以在家看电影、追剧但是小屏看剧一点也不爽何不投放到电视上饱览大视野呢我们可以借助“投屏”功能痛痛快快在电视上观看想看的剧集和电影那么如何通过手机,将内容传送到智能电视上呢那么接下来为大家介绍…

ImportError: No module named ‘pandas.io.data‘

ImportError: No module named pandas.io.data 第一步:pip install pandas-datareader 第二步: 把 "from pandas.io.data import DataReader" 换成 "from pandas_datareader import data"

分类算法之决策树介绍

实习了一段时间,接触了一些数据挖掘、机器学习的算法,先记录下来方便以后的复习回顾: 一:决策树概念 决策树可以看做一个树状预测模型,它是由节点和有向边组成的层次结构。树中包含3中节点:根节点、内部节点…

C#调用Couchbase中的Memcached缓存

安装服务端 服务端下载地址:http://www.couchbase.com/download 选择适合自己的进行下载安装就可以了,我这里选择的是Win7 64。 服务端安装完后,如果成功了,那么在浏览器中可以看到。如果没有那么需要手动进行访问http://localhost:8091/ind…

Windows10安装Anaconda和Pytorch(CPU版,无GPU加速)

1.Anaconda安装 Anaconda的安装网上的教程非常非常多,很简单,下面这篇博客写的很详细,看我写的也可以。 地址:https://blog.csdn.net/u014546828/article/details/80334448 注意:不建议从 官网下载,官网…

云计算的发展及应用--演讲用PPT

最近在几个客户处进行了关于云计算的普及培训。主要是让用户了解什么是云计算,云计算的框架以及对我们的影响。我将自己手中的几本相关资料,结合自己的经验和理解,整合成了一篇演示用的PPT。 虽然演示用的PPT简洁些,但用来理解一下…

nodejs Error: request entity too large解决方案

错误如图: 解决方案: app.js添加 var bodyParser require(body-parser);app.use(bodyParser.json({limit: 50mb}));app.use(bodyParser.urlencoded({limit: 50mb, extended: true}));

閱讀10大優點:為什麼你應該每天閱讀

閱讀10大優點:為什麼你應該每天閱讀當是你最後一次讀一本書,或主要雜誌上的文章?你的日常的閱讀習慣圍繞推特,Facebook的更新或速溶燕麥片包上的指示?如果你是其中之一,無數的人誰不經常閱讀的習慣&#xf…

Node出错导致运行崩溃的解决方案

许多人都有这样一种映像,NodeJS比较快; 但是因为其是单线程,所以它不稳定,有点不安全,不适合处理复杂业务; 它比较适合对并发要求比较高,而且简单的业务场景。 在Express的作者的TJ Holowaychuk…

python回测量化交易策略收益率

本篇我们将对比经典量化回测框架pyalgotrade与ailabx,二者同时实现均线策略。 “积木式”实现策略示例 “买入并持有”策略: buy_and_hold Strategy([ RunOnce(), PrintBar(),SelectAll(),WeighEqually(),]) “均线交叉策略”: long_ex…

移动端HTML5框架

一:移动端HTML5框架 http://jquerymobile.com/jQuery Mobilehttp://jqtjs.com/jQTouchhttp://www.sencha.com/products/touchSencha Touch二:三大框架区别 http://mobile.51cto.com/web-321296.htmhttp://www.leiphone.com/0907-warlial-html5-framework…

nodejs基于art-template模板引擎生成

基础核心代码 var template require(art-template);var tName new Date().getTime();var htmlT <!DOCTYPE html><html lang"en"><head><meta charset"UTF-8"><title></title></head><body><h1>{…

Pyalgotrade量化交易回测框架

现在就开始干活了。先要测试一下pyalgotrade回测数据对不对。我找了个参照标准:在聚宽上开通了个账号&#xff0c;按入门教程写了个策略:2016-2018年每个交易日买入100股平安银行(000001)&#xff0c;回测结果如下: 现在用pyalgotrade来实现一下这个策略。先用tushare下载平安银…

1.4三态缓存(tristate buffer)与 多路复用器(Multiplexers)

首先解释名词。由于想了好多例子&#xff0c;结果发现没有太好的。于是换一种办法&#xff0c;直接上图和真值表。。这个东西就是多路复用器&#xff08;MUX&#xff09;从图中和真值表可以总结出&#xff1a;当s为0选择D0通过&#xff0c;也就是YD0&#xff0c;而不在乎D1上的…

art-template用户注册方法

应用场景nodejs Express框架&#xff0c;使用art-template模板引擎。 后台注册方法代码&#xff1a; var template require(art-template);template.helper(myRegFunc, function (str1, str2) {return "我是后台方法: " str1 str2;}); 前台使用&#xff1a; <…

如何导出已安装的安卓app为apk包

下载 “夜神模拟器” &#xff0c; 鼠标长安应用&#xff0c;拖拽到 “apk导出”处 即可