nodejs操作sqlserver数据_nodejs + express + mssql 封装数据操作

本文档介绍了如何使用Node.js、Express和mssql库封装SQL Server数据库操作。通过创建db.js文件,实现了包括查询、添加、更新、删除在内的基本数据库操作,并提供了config.js配置示例。在实际应用中,这些封装的方法可以方便地在Express路由中调用,实现对新闻数据的CRUD操作。
摘要由CSDN通过智能技术生成

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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值