在網上看到有一些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的使用函數