在網上看到有一些nodejs連線sqlserver的相關教程,但非常少,而且很多都有錯,特別是運算元據庫的語句,在這裡我做了一番整理,搭建一個完整的nodejs後臺,並封裝sqlserver的操作。
nodejs的安裝和express的安裝在這裡就不多說,網上都有教程,不會的網上一搜都有。
然後安裝mssql,在terminal中進入你的專案資料夾,輸入命令:npm install mssql
,等待片刻,即完成了安裝。
這個時候新建一個db.js(名字隨便),開始封裝資料操作。我一般會新建一個與routes,views同級的資料夾,放一些公共的js,比如分頁函式分封裝page.js等等。下面開始封裝資料庫。
先放程式碼:
/**
*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:
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為例:
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的使用