/**
* Created by Administrator on 2015/9/14.
*/
var node_mssql = require('node-mssql');
/* add configuration to query object */
var host = '192.168.20.135',
port = 1433,
username = 'sa',
password = 'sa',
db = 'GG_ChatDB';
var queryObj = new node_mssql.Query({
host: host,
port: port,
username: username,
password: password,
db: db
});
var initDbHelper = function (host,port,username,password,db) {
queryObj = new node_mssql.Query({
host: host,
port: port,
username: username,
password: password,
db: db
});
}
var defaultConfig = function () {
queryObj = new node_mssql.Query({
host: host,
db: db
});
}
var insert = function (data,insertTable,callback,res) {
queryObj.table(insertTable);
queryObj.data(data);
queryObj.insert(function (results) {
//success
callback(res,"添加成功!",results);
},function (err,sql) {
if (err) {//error
callback(res,"添加失败!",err);
console.log(err);
}
});
defaultConfig();
};
var list = function (whereSql,orderList,table,res) {
queryObj.table(table);
queryObj.where(whereSql);
queryObj.order(orderList); // ['id desc',...]
queryObj.select(function (data) {
//success
callback(res,"查询成功!",data);
},sql) {
if (err) { //error
callback(res,"查询失败!",err);
console.log(err);
}
});
defaultConfig();
};
var update = function (data,option,upTable,res) {
queryObj.table(upTable);
queryObj.data(data);
queryObj.where(option);
queryObj.update(function (results) {
// success callback
callback(res,"修改成功!",sql) {
if (err) {
callback(res,"修改失败!",err);
console.log(err);
}
});
defaultConfig();
};
//参数说明:@delsql删除sql条件,举例 delsql="id=1"
var deleteById = function (delsql,res) {
queryObj.query("delete from " + table + " where " + delsql,
function (delres) {
callback(res,"删除成功!",delres);
},
function (err,sql) {
if (err) {
callback(res,"删除失败!",err);
}
}
);
defaultConfig();
};
var queryBySql = function (sql,res) {
queryObj.query(sql,function (delres) {
callback(res,"执行成功!","执行失败!",err);
}
}
);
defaultConfig();
}
exports.insert = insert;
exports.list = list;
exports.update = update;
exports.deleteById = deleteById;
exports.initDbHelper = initDbHelper;
exports.queryBySql = queryBySql;
var express = require('express');
var dbHelper = require('./dbHelper.js');
var router = express.Router();
/* GET home page. */
router.get('/',function (req,res,next) {
dbHelper.list({},'dbo.table1',res);
// list参数,第一个是whereSql查询条件,json格式;第二个是表名,第三个是回调函数,第四个是express返回客户端的response类
});
var callback = (data,res) {
res.render('list' 第一个参数:模板名称对应list.ejs,第二个是参数名和数据
};
module.exports = router;
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css'/>
</head>
<body>
<ul>
<% for(var i = 0; i < listData.length; i++) { %>
<li><%= listData[i].Id %> : <%= listData[i].Name %></li>
<% } %>
</ul>
</body>
</html>