node.js连接SQLserver数据库实践

 更新时间:2026年03月27日 09:12:25   作者:小沐°  
这篇文章主要介绍了node.js连接SQLserver数据库实践方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1.在自己的项目JS文件夹中建文件

config.js、mssql.js和server.js以及api文件夹下的user.js

2.在config.js中封装数据库信息

let app = {
  user: 'sa', //这里写你的数据库的用户名
  password: '',//这里写数据库的密码
  server: 'localhost',
  database: 'medicineSystem', // 数据库名字
  port: 1433, //端口号,默认1433
  options: {
    encrypt: false,  //加密,设置为true时会连接失败 Failed to connect to localhost:1433 - self signed certificate
    enableArithAbort: false
  },
  pool: {
    min: 0,
    max: 10,
    idleTimeoutMillis: 3000
  }
}

module.exports = app

3.在mssql.js中对sql语句的二次封装

//mssql.js
/**
 *sqlserver Model
 **/
const mssql = require("mssql");
const conf = require("./config.js");

const pool = new mssql.ConnectionPool(conf)
const poolConnect = pool.connect()

pool.on('error', err => {
  console.log('error: ', err)
})
/**
 * 自由查询
 * @param sql sql语句,例如: 'select * from news where id = @id'
 * @param params 参数,用来解释sql中的@*,例如: { id: id }
 * @param callBack 回调函数
 */
let querySql = async function (sql, params, callBack) {
  try {
    let ps = new mssql.PreparedStatement(await poolConnect);
    if (params != "") {
      for (let 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, function (err) {
      if (err)
        console.log(err);
      ps.execute(params, function (err, recordset) {
        callBack(err, recordset);
        ps.unprepare(function (err) {
          if (err)
            console.log(err);
        });
      });
    });
  } catch (e) {
    console.log(e)
  }
};

/**
 * 按条件和需求查询指定表
 * @param tableName 数据库表名,例:'news'
 * @param topNumber 只查询前几个数据,可为空,为空表示查询所有
 * @param whereSql 条件语句,例:'where id = @id'
 * @param params 参数,用来解释sql中的@*,例如: { id: id }
 * @param orderSql 排序语句,例:'order by created_date'
 * @param callBack 回调函数
 */
let select = async function (tableName, topNumber, whereSql, params, orderSql, callBack) {
  try {
    let ps = new mssql.PreparedStatement(await poolConnect);
    let sql = "select * from " + tableName + " ";
    if (topNumber != "") {
      sql = "select top(" + topNumber + ") * from " + tableName + " ";
    }
    sql += whereSql + " ";
    if (params != "") {
      for (let 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, function (err) {
      if (err)
        console.log(err);
      ps.execute(params, function (err, recordset) {
        callBack(err, recordset);
        ps.unprepare(function (err) {
          if (err)
            console.log(err);
        });
      });
    });
  } catch (e) {
    console.log(e)
  }
};

/**
 * 查询指定表的所有数据
 * @param tableName 数据库表名
 * @param callBack 回调函数
 */
let selectAll = async function (tableName, callBack) {
  try {
    let ps = new mssql.PreparedStatement(await poolConnect);
    let sql = "select * from " + tableName + " ";
    ps.prepare(sql, function (err) {
      if (err)
        console.log(err);
      ps.execute("", function (err, recordset) {
        callBack(err, recordset);
        ps.unprepare(function (err) {
          if (err)
            console.log(err);
        });
      });
    });
  } catch (e) {
    console.log(e)
  }
};

/**
 * 添加字段到指定表
 * @param addObj 需要添加的对象字段,例:{ name: 'name', age: 20 }
 * @param tableName 数据库表名
 * @param callBack 回调函数
 */
let add = async function (addObj, tableName, callBack) {
  try {
    let ps = new mssql.PreparedStatement(await poolConnect);
    let sql = "insert into " + tableName + "(";
    if (addObj != "") {
      for (let 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 (let 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) + ") SELECT @@IDENTITY id"; // 加上SELECT @@IDENTITY id才会返回id
    ps.prepare(sql, function (err) {
      if (err) console.log(err);
      ps.execute(addObj, function (err, recordset) {
        callBack(err, recordset);
        ps.unprepare(function (err) {
          if (err)
            console.log(err);
        });
      });
    });
  } catch (e) {
    console.log(e)
  }
};

/**
 * 更新指定表的数据
 * @param updateObj 需要更新的对象字段,例:{ name: 'name', age: 20 }
 * @param whereObj 需要更新的条件,例: { id: id }
 * @param tableName 数据库表名
 * @param callBack 回调函数
 */
let update = async function (updateObj, whereObj, tableName, callBack) {
  try {
    let ps = new mssql.PreparedStatement(await poolConnect);
    let sql = "update " + tableName + " set ";
    if (updateObj != "") {
      for (let 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 (let 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, function (err) {
      if (err)
        console.log(err);
      ps.execute(updateObj, function (err, recordset) {
        callBack(err, recordset);
        ps.unprepare(function (err) {
          if (err)
            console.log(err);
        });
      });
    });
  } catch (e) {
    console.log(e)
  }
};

/**
 * 删除指定表字段
 * @param whereSql 要删除字段的条件语句,例:'where id = @id'
 * @param params 参数,用来解释sql中的@*,例如: { id: id }
 * @param tableName 数据库表名
 * @param callBack 回调函数
 */
let del = async function (whereSql, params, tableName, callBack) {
  try {
    let ps = new mssql.PreparedStatement(await poolConnect);
    let sql = "delete from " + tableName + " ";
    if (params != "") {
      for (let 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, function (err) {
      if (err)
        console.log(err);
      ps.execute(params, function (err, recordset) {
        callBack(err, recordset);
        ps.unprepare(function (err) {
          if (err)
            console.log(err);
        });
      });
    });
  } catch (e) {
    console.log(e)
  }
};

exports.config = conf;
exports.del = del;
exports.select = select;
exports.update = update;
exports.querySql = querySql;
exports.selectAll = selectAll;
exports.add = add;

4.在api/user.js下写接口代码

//user.js
const express = require('express');
const db = require('../mssql.js');
const moment = require('moment');
const router = express.Router();

/* GET home page. */
router.get('/medicineList', function (req, res, next) {//查询某表下的全部数据
  db.selectAll('medicineList', function (err, result) {
    res.send(result.recordset)
  });
});
router.get('/medicineAssess', function (req, res, next) {
  db.selectAll('medicineAssess', function (err, result) {
    res.send(result.recordset)
  });
});
router.get('/medicineAsk', function (req, res, next) {
  db.selectAll('medicineAsk', function (err, result) {
    res.send(result.recordset)
  });
});
router.get('/diseaseList', function (req, res, next) {
  db.selectAll('diseaseList', function (err, result) {
    res.send(result.recordset)
  });
});
router.get('/diseaseMedicine', function (req, res, next) {
  db.selectAll('diseaseMedicine', function (err, result) {
    res.send(result.recordset)
  });
});
router.get('/user', function (req, res, next) {
  db.selectAll('user', function (err, result) {
    res.send(result.recordset)
  });
});
router.get('/admin', function (req, res, next) {
  db.selectAll('admin', function (err, result) {
    res.send(result.recordset)
  });
});
router.post('/delete', function (req, res, next) {//删除一条id对应的userInfo表的数据
  const { UserId } = req.body
  const id = UserId
  db.del("where id = @id", { id: id }, "userInfo", function (err, result) {
    console.log(result, 66);
    res.send('ok')
  });
});
router.post('/update/:id', function (req, res, next) {//更新一条对应id的userInfo表的数据
  var id = req.params.id;
  var content = req.body.content;
  db.update({ content: content }, { id: id }, "userInfo", function (err, result) {
    res.redirect('back');
  });
});

module.exports = router;

5.在server.js中配置启动文件

//1.导入模块
const express = require('express')

//2.创建服务器
let server = express()
server.use(express.urlencoded()) //中间件要写在启动文件里面

const cors = require('cors')
server.use(cors())

const user = require('./api/user.js')

server.use('/', user)

//3.开启服务器
server.listen(8002, () => {
  console.log('服务器已启动,在端口号8002')
})

6.启动服务器

cmd到server.js所在的目录下输入:

nodemon server.js

7.用postman测试接口

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • node.js中的events.EventEmitter.listenerCount方法使用说明

    node.js中的events.EventEmitter.listenerCount方法使用说明

    这篇文章主要介绍了node.js中的events.EventEmitter.listenerCount方法使用说明,本文介绍了events.EventEmitter.listenerCount的方法说明、语法、使用实例和实现源码,需要的朋友可以参考下
    2014-12-12
  • Nest.js散列与加密实例详解

    Nest.js散列与加密实例详解

    这篇文章主要给大家介绍了关于Nest.js散列与加密的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Node.js中用D3.js的方法示例

    Node.js中用D3.js的方法示例

    这篇文章主要给大家介绍了在Node.js中用D3.js的方法,文中分别介绍了如何安装模块和一小段简单的示例代码,有需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-01-01
  • node.js 使用 net 模块模拟 websocket 握手进行数据传递操作示例

    node.js 使用 net 模块模拟 websocket 握手进行数据传递操作示例

    这篇文章主要介绍了node.js 使用 net 模块模拟 websocket 握手进行数据传递操作,结合实例形式分析了node.js基于net模块模拟 websocket握手相关原理及进行数据传递具体操作技巧,需要的朋友可以参考下
    2020-02-02
  • npm 常用命令详解(小结)

    npm 常用命令详解(小结)

    这篇文章主要介绍了npm 常用命令详解(小结),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • 详解如何修改 node_modules 里的文件

    详解如何修改 node_modules 里的文件

    这篇文章主要介绍了详解如何修改node_modules里的文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • 详解Node.js开发中的express-session

    详解Node.js开发中的express-session

    express-session 是基于express框专门用于处理session的中间件,本篇文章主要介绍了详解Node.js开发中的express-session,有兴趣的可以了解一下<BR>
    2017-05-05
  • Node中fs文件系统模块的使用方法详解

    Node中fs文件系统模块的使用方法详解

    fs 模块是 Node.js 官方提供的、用来操作文件的模块(内置api),它提供了一系列的方法和属性,用来满足用户对文件的操作需求,本文给大家介绍了Node中fs文件系统模块的使用方法,需要的朋友可以参考下
    2024-03-03
  • 为什么Node.js会这么火呢?Node.js流行的原因

    为什么Node.js会这么火呢?Node.js流行的原因

    是什么原因让Node.js突然间如此流行呢?听起来像是有了一种新的Web开发技术,是这样吗?我们来汇总一下。
    2014-12-12
  • node.js实现学生档案管理

    node.js实现学生档案管理

    这篇文章主要为大家详细介绍了node.js实现学生档案管理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05

最新评论