当前位置:   article > 正文

node.js-连接SQLserver数据库_nodejs连接mssql

nodejs连接mssql

1.在自己的项目JS文件夹中建文件:config.js、mssql.js和server.js以及api文件夹下的user.js

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

  1. let app = {
  2. user: 'sa', //这里写你的数据库的用户名
  3. password: '',//这里写数据库的密码
  4. server: 'localhost',
  5. database: 'medicineSystem', // 数据库名字
  6. port: 1433, //端口号,默认1433
  7. options: {
  8. encrypt: false, //加密,设置为true时会连接失败 Failed to connect to localhost:1433 - self signed certificate
  9. enableArithAbort: false
  10. },
  11. pool: {
  12. min: 0,
  13. max: 10,
  14. idleTimeoutMillis: 3000
  15. }
  16. }
  17. module.exports = app

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

  1. //mssql.js
  2. /**
  3. *sqlserver Model
  4. **/
  5. const mssql = require("mssql");
  6. const conf = require("./config.js");
  7. const pool = new mssql.ConnectionPool(conf)
  8. const poolConnect = pool.connect()
  9. pool.on('error', err => {
  10. console.log('error: ', err)
  11. })
  12. /**
  13. * 自由查询
  14. * @param sql sql语句,例如: 'select * from news where id = @id'
  15. * @param params 参数,用来解释sql中的@*,例如: { id: id }
  16. * @param callBack 回调函数
  17. */
  18. let querySql = async function (sql, params, callBack) {
  19. try {
  20. let ps = new mssql.PreparedStatement(await poolConnect);
  21. if (params != "") {
  22. for (let index in params) {
  23. if (typeof params[index] == "number") {
  24. ps.input(index, mssql.Int);
  25. } else if (typeof params[index] == "string") {
  26. ps.input(index, mssql.NVarChar);
  27. }
  28. }
  29. }
  30. ps.prepare(sql, function (err) {
  31. if (err)
  32. console.log(err);
  33. ps.execute(params, function (err, recordset) {
  34. callBack(err, recordset);
  35. ps.unprepare(function (err) {
  36. if (err)
  37. console.log(err);
  38. });
  39. });
  40. });
  41. } catch (e) {
  42. console.log(e)
  43. }
  44. };
  45. /**
  46. * 按条件和需求查询指定表
  47. * @param tableName 数据库表名,例:'news'
  48. * @param topNumber 只查询前几个数据,可为空,为空表示查询所有
  49. * @param whereSql 条件语句,例:'where id = @id'
  50. * @param params 参数,用来解释sql中的@*,例如: { id: id }
  51. * @param orderSql 排序语句,例:'order by created_date'
  52. * @param callBack 回调函数
  53. */
  54. let select = async function (tableName, topNumber, whereSql, params, orderSql, callBack) {
  55. try {
  56. let ps = new mssql.PreparedStatement(await poolConnect);
  57. let sql = "select * from " + tableName + " ";
  58. if (topNumber != "") {
  59. sql = "select top(" + topNumber + ") * from " + tableName + " ";
  60. }
  61. sql += whereSql + " ";
  62. if (params != "") {
  63. for (let index in params) {
  64. if (typeof params[index] == "number") {
  65. ps.input(index, mssql.Int);
  66. } else if (typeof params[index] == "string") {
  67. ps.input(index, mssql.NVarChar);
  68. }
  69. }
  70. }
  71. sql += orderSql;
  72. console.log(sql);
  73. ps.prepare(sql, function (err) {
  74. if (err)
  75. console.log(err);
  76. ps.execute(params, function (err, recordset) {
  77. callBack(err, recordset);
  78. ps.unprepare(function (err) {
  79. if (err)
  80. console.log(err);
  81. });
  82. });
  83. });
  84. } catch (e) {
  85. console.log(e)
  86. }
  87. };
  88. /**
  89. * 查询指定表的所有数据
  90. * @param tableName 数据库表名
  91. * @param callBack 回调函数
  92. */
  93. let selectAll = async function (tableName, callBack) {
  94. try {
  95. let ps = new mssql.PreparedStatement(await poolConnect);
  96. let sql = "select * from " + tableName + " ";
  97. ps.prepare(sql, function (err) {
  98. if (err)
  99. console.log(err);
  100. ps.execute("", function (err, recordset) {
  101. callBack(err, recordset);
  102. ps.unprepare(function (err) {
  103. if (err)
  104. console.log(err);
  105. });
  106. });
  107. });
  108. } catch (e) {
  109. console.log(e)
  110. }
  111. };
  112. /**
  113. * 添加字段到指定表
  114. * @param addObj 需要添加的对象字段,例:{ name: 'name', age: 20 }
  115. * @param tableName 数据库表名
  116. * @param callBack 回调函数
  117. */
  118. let add = async function (addObj, tableName, callBack) {
  119. try {
  120. let ps = new mssql.PreparedStatement(await poolConnect);
  121. let sql = "insert into " + tableName + "(";
  122. if (addObj != "") {
  123. for (let index in addObj) {
  124. if (typeof addObj[index] == "number") {
  125. ps.input(index, mssql.Int);
  126. } else if (typeof addObj[index] == "string") {
  127. ps.input(index, mssql.NVarChar);
  128. }
  129. sql += index + ",";
  130. }
  131. sql = sql.substring(0, sql.length - 1) + ") values(";
  132. for (let index in addObj) {
  133. if (typeof addObj[index] == "number") {
  134. sql += addObj[index] + ",";
  135. } else if (typeof addObj[index] == "string") {
  136. sql += "'" + addObj[index] + "'" + ",";
  137. }
  138. }
  139. }
  140. sql = sql.substring(0, sql.length - 1) + ") SELECT @@IDENTITY id"; // 加上SELECT @@IDENTITY id才会返回id
  141. ps.prepare(sql, function (err) {
  142. if (err) console.log(err);
  143. ps.execute(addObj, function (err, recordset) {
  144. callBack(err, recordset);
  145. ps.unprepare(function (err) {
  146. if (err)
  147. console.log(err);
  148. });
  149. });
  150. });
  151. } catch (e) {
  152. console.log(e)
  153. }
  154. };
  155. /**
  156. * 更新指定表的数据
  157. * @param updateObj 需要更新的对象字段,例:{ name: 'name', age: 20 }
  158. * @param whereObj 需要更新的条件,例: { id: id }
  159. * @param tableName 数据库表名
  160. * @param callBack 回调函数
  161. */
  162. let update = async function (updateObj, whereObj, tableName, callBack) {
  163. try {
  164. let ps = new mssql.PreparedStatement(await poolConnect);
  165. let sql = "update " + tableName + " set ";
  166. if (updateObj != "") {
  167. for (let index in updateObj) {
  168. if (typeof updateObj[index] == "number") {
  169. ps.input(index, mssql.Int);
  170. sql += index + "=" + updateObj[index] + ",";
  171. } else if (typeof updateObj[index] == "string") {
  172. ps.input(index, mssql.NVarChar);
  173. sql += index + "=" + "'" + updateObj[index] + "'" + ",";
  174. }
  175. }
  176. }
  177. sql = sql.substring(0, sql.length - 1) + " where ";
  178. if (whereObj != "") {
  179. for (let index in whereObj) {
  180. if (typeof whereObj[index] == "number") {
  181. ps.input(index, mssql.Int);
  182. sql += index + "=" + whereObj[index] + " and ";
  183. } else if (typeof whereObj[index] == "string") {
  184. ps.input(index, mssql.NVarChar);
  185. sql += index + "=" + "'" + whereObj[index] + "'" + " and ";
  186. }
  187. }
  188. }
  189. sql = sql.substring(0, sql.length - 5);
  190. ps.prepare(sql, function (err) {
  191. if (err)
  192. console.log(err);
  193. ps.execute(updateObj, function (err, recordset) {
  194. callBack(err, recordset);
  195. ps.unprepare(function (err) {
  196. if (err)
  197. console.log(err);
  198. });
  199. });
  200. });
  201. } catch (e) {
  202. console.log(e)
  203. }
  204. };
  205. /**
  206. * 删除指定表字段
  207. * @param whereSql 要删除字段的条件语句,例:'where id = @id'
  208. * @param params 参数,用来解释sql中的@*,例如: { id: id }
  209. * @param tableName 数据库表名
  210. * @param callBack 回调函数
  211. */
  212. let del = async function (whereSql, params, tableName, callBack) {
  213. try {
  214. let ps = new mssql.PreparedStatement(await poolConnect);
  215. let sql = "delete from " + tableName + " ";
  216. if (params != "") {
  217. for (let index in params) {
  218. if (typeof params[index] == "number") {
  219. ps.input(index, mssql.Int);
  220. } else if (typeof params[index] == "string") {
  221. ps.input(index, mssql.NVarChar);
  222. }
  223. }
  224. }
  225. sql += whereSql;
  226. ps.prepare(sql, function (err) {
  227. if (err)
  228. console.log(err);
  229. ps.execute(params, function (err, recordset) {
  230. callBack(err, recordset);
  231. ps.unprepare(function (err) {
  232. if (err)
  233. console.log(err);
  234. });
  235. });
  236. });
  237. } catch (e) {
  238. console.log(e)
  239. }
  240. };
  241. exports.config = conf;
  242. exports.del = del;
  243. exports.select = select;
  244. exports.update = update;
  245. exports.querySql = querySql;
  246. exports.selectAll = selectAll;
  247. exports.add = add;

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

  1. //user.js
  2. const express = require('express');
  3. const db = require('../mssql.js');
  4. const moment = require('moment');
  5. const router = express.Router();
  6. /* GET home page. */
  7. router.get('/medicineList', function (req, res, next) {//查询某表下的全部数据
  8. db.selectAll('medicineList', function (err, result) {
  9. res.send(result.recordset)
  10. });
  11. });
  12. router.get('/medicineAssess', function (req, res, next) {
  13. db.selectAll('medicineAssess', function (err, result) {
  14. res.send(result.recordset)
  15. });
  16. });
  17. router.get('/medicineAsk', function (req, res, next) {
  18. db.selectAll('medicineAsk', function (err, result) {
  19. res.send(result.recordset)
  20. });
  21. });
  22. router.get('/diseaseList', function (req, res, next) {
  23. db.selectAll('diseaseList', function (err, result) {
  24. res.send(result.recordset)
  25. });
  26. });
  27. router.get('/diseaseMedicine', function (req, res, next) {
  28. db.selectAll('diseaseMedicine', function (err, result) {
  29. res.send(result.recordset)
  30. });
  31. });
  32. router.get('/user', function (req, res, next) {
  33. db.selectAll('user', function (err, result) {
  34. res.send(result.recordset)
  35. });
  36. });
  37. router.get('/admin', function (req, res, next) {
  38. db.selectAll('admin', function (err, result) {
  39. res.send(result.recordset)
  40. });
  41. });
  42. router.post('/delete', function (req, res, next) {//删除一条id对应的userInfo表的数据
  43. const { UserId } = req.body
  44. const id = UserId
  45. db.del("where id = @id", { id: id }, "userInfo", function (err, result) {
  46. console.log(result, 66);
  47. res.send('ok')
  48. });
  49. });
  50. router.post('/update/:id', function (req, res, next) {//更新一条对应id的userInfo表的数据
  51. var id = req.params.id;
  52. var content = req.body.content;
  53. db.update({ content: content }, { id: id }, "userInfo", function (err, result) {
  54. res.redirect('back');
  55. });
  56. });
  57. module.exports = router;

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

  1. //1.导入模块
  2. const express = require('express')
  3. //2.创建服务器
  4. let server = express()
  5. server.use(express.urlencoded()) //中间件要写在启动文件里面
  6. const cors = require('cors')
  7. server.use(cors())
  8. const user = require('./api/user.js')
  9. server.use('/', user)
  10. //3.开启服务器
  11. server.listen(8002, () => {
  12. console.log('服务器已启动,在端口号8002')
  13. })

6.启动服务器

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

nodemon server.js

7.用postman测试接口

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/717444
推荐阅读
相关标签
  

闽ICP备14008679号