在网上看到有一些nodejs链接sqlserver的相关教程,但很是少,并且不少都有错,特别是操做数据库的语句,在这里我作了一番整理,搭建一个完整的nodejs后台,并封装sqlserver的操做。node
nodejs的安装和express的安装在这里就很少说,网上都有教程,不会的网上一搜都有。sql
而后安装mssql,在terminal中进入你的项目文件夹,输入命令:npm install mssql
,等待片刻,即完成了安装。数据库
这个时候新建一个db.js(名字随便),开始封装数据操做。我通常会新建一个与routes,views同级的文件夹,放一些公共的js,好比分页函数分封装page.js等等。下面开始封装数据库。express
先放代码:npm
/** *sqlserver Model **/ const mssql = require("mssql"); const util = require("util"); const conf = require("../config.js"); let restoreDefaults = function () { conf; }; const con = new mssql.ConnectionPool(conf); con.on('error', err => { if (err) { throw err; } }); con.connect(err => { if (err) { console.error(err); } }); let querySql = async function (sql, params, callBack) { try{ let ps = new mssql.PreparedStatement(con); 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); } } } ps.prepare(sql, err => { if (err) console.log(err); ps.execute(params, (err, recordset) => { callBack(err, recordset); ps.unprepare(err => { if (err) console.log(err); }); }); }); }catch(err){ console.error('SQL error', err); } restoreDefaults(); }; var select = async function (tableName, topNumber, whereSql, params, orderSql, callBack) { try{ var ps = new mssql.PreparedStatement(con); 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, err => { if (err) console.log(err); ps.execute(params, (err, recordset) => { callBack(err, recordset); ps.unprepare(err => { if (err) console.log(err); }); }); }); }catch(err){ console.error('SQL error', err); } restoreDefaults(); }; var selectAll = async function (tableName, callBack) { try{ var ps = new mssql.PreparedStatement(con); var sql = "select * from " + tableName + " "; ps.prepare(sql, err => { if (err) console.log(err); ps.execute("", (err, recordset) => { callBack(err, recordset); ps.unprepare(err => { if (err) console.log(err); }); }); }); }catch(err){ console.error('SQL error', err); } restoreDefaults(); }; var add = async function (addObj, tableName, callBack) { try{ var ps = new mssql.PreparedStatement(con); 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) + ")"; ps.prepare(sql, err => { if (err) console.log(err); ps.execute(addObj, (err, recordset) => { callBack(err, recordset); ps.unprepare(err => { if (err) console.log(err); }); }); }); }catch(err){ console.error('SQL error', err); } restoreDefaults(); }; var update = async function (updateObj, whereObj, tableName, callBack) { try{ var ps = new mssql.PreparedStatement(con); var sql = "update " + tableName + " set "; 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); ps.prepare(sql, err => { if (err) console.log(err); ps.execute(updateObj, (err, recordset) => { callBack(err, recordset); ps.unprepare(err => { if (err) console.log(err); }); }); }); }catch(err){ console.error('SQL error', err); } restoreDefaults(); }; var del = async function (whereSql, params, tableName, callBack) { try{ var ps = new mssql.PreparedStatement(con); 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; ps.prepare(sql, err => { if (err) console.log(err); ps.execute(params, (err, recordset) => { callBack(err, recordset); ps.unprepare(err => { if (err) console.log(err); }); }); }); }catch(err){ console.error('SQL error', err); } restoreDefaults(); }; exports.config = conf; exports.del = del; exports.select = select; exports.update = update; exports.querySql = querySql; exports.selectAll = selectAll; exports.restoreDefaults = restoreDefaults; exports.add = add;
在这里还须要一个config.js:app
let app = { user: 'sa', password: '', server: 'localhost', database: 'database', port: 1433, options: { encrypt: true // Use this if you're on Windows Azure }, pool: { min: 0, max: 10, idleTimeoutMillis: 3000 } }; module.exports = app;
这就完成了封装,网上不少教程都是用的mssql.Connection()
可是会发现有些会报错并无这个函数,还有些改为mssql.connect()
,虽然能够了,可是在第二次用到数据库的地方就会报错大体是你的数据库已经链接,须要关闭后才能够再链接。而用mssql.ConnectionPool()
就没有这些问题,下面是使用,以index.js为例:async
var express = require('express'); var db = require('../utils/db.js'); var moment = require('moment'); var router = express.Router(); /* GET home page. */ router.get('/', function (req, res, next) { db.selectAll('news', function (err, result) {//查询全部news表的数据 res.render('newsList', {results:records.recordset, moment:moment}); }); }); router.get('/delete/:id', function (req, res, next) {//删除一条id对应的news表的数据 var id = req.params.id; db.del("where id = @id", {id:id}, "news", function(err, result){ res.redirect('back');//返回前一个页面 }); }); router.post('/update/:id', function (req, res, next) {//更新一条对应id的news表的数据 var id = req.params.id; var content = req.body.content; db.update({content:content}, {id:id}, "news", function(err, result){ res.redirect('back'); }); }); module.exports = router;
这样就实现了nodejs和mssql的使用函数