当前位置: 首页 > news >正文

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, //端口号,默认1433options: {encrypt: false,  //加密,设置为true时会连接失败 Failed to connect to localhost:1433 - self signed certificateenableArithAbort: 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才会返回idps.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.bodyconst id = UserIddb.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-连接SQLserver数据库

1.在自己的项目JS文件夹中建文件:config.js、mssql.js和server.js以及api文件夹下的user.js 2.在config.js中封装数据库信息 let app {user: sa, //这里写你的数据库的用户名password: ,//这里写数据库的密码server: localhost,database: medicineSystem, // 数据…...

目标检测YOLO系列从入门到精通技术详解100篇-【图像处理】图像预处理方法

目录 前言 知识储备 Opencv图像操作 几个高频面试题目 为什么需要图像算法? 算法原理...

Android drawable layer-list右上角红点,xml布局实现,Kotlin

Android drawable layer-list右上角红点&#xff0c;xml布局实现&#xff0c;Kotlin <?xml version"1.0" encoding"utf-8"?> <layer-list xmlns:android"http://schemas.android.com/apk/res/android"><itemandroid:id"id…...

网络虚拟化场景下网络包的发送过程

网络虚拟化有和存储虚拟化类似的地方&#xff0c;例如&#xff0c;它们都是基于 virtio 的&#xff0c;因而在看网络虚拟化的过程中&#xff0c;会看到和存储虚拟化很像的数据结构和原理。但是&#xff0c;网络虚拟化也有自己的特殊性。例如&#xff0c;存储虚拟化是将宿主机上…...

《数据结构与测绘程序设计》试题详细解析(仅供参考)

一. 选择题&#xff08;每空2分&#xff0c;本题共30分&#xff09; &#xff08;1&#xff09;在一个单链表中&#xff0c;已知q所指结点是p所指结点的前驱结点&#xff0c;若在q和p之间插入结点s&#xff0c;则执行( B )。 A. s->nextp->next; p->nexts; B. q…...

Raft 算法

Raft 算法 1 背景 当今的数据中心和应用程序在高度动态的环境中运行&#xff0c;为了应对高度动态的环境&#xff0c;它们通过额外的服务器进行横向扩展&#xff0c;并且根据需求进行扩展和收缩。同时&#xff0c;服务器和网络故障也很常见。 因此&#xff0c;系统必须在正常…...

Redis队列stream,Redis多线程详解

Redis 目前最新版本为 Redis-6.2.6 &#xff0c;会以 CentOS7 下 Redis-6.2.4 版本进行讲解。 下载地址&#xff1a; https://redis.io/download 安装运行 Redis 很简单&#xff0c;在 Linux 下执行上面的 4 条命令即可 &#xff0c;同时前面的 课程已经有完整的视…...

ThinkPHP的方法接收json数据问题

第一次接触到前后端分离开发&#xff0c;需要在后端接收前端ajax提交的json数据&#xff0c;开发基于ThinkPHP3.2.3框架。于是一开始习惯性的直接用I()方法接收到前端发送的json数据&#xff0c;然后用json_decode()解析发现结果为空&#xff01;但是打印出还未解析的值却打印得…...

简单理解算法

简单理解算法 前言算法衡量一个好的算法具备的标准算法的应用场景 数据结构数据结构的组成方式 前言 hello&#xff0c;宝宝们~来分享我从一本书中理解的算法。《漫画算法》感觉对我这种算法小白比较友好。看完感觉对算法有了新的理解&#xff0c;计算机学习这么多年&#xff…...

C/C++ 内存管理(2)

文章目录 new 和 delet 概念new 和 delet 的使用new与 delete 底层原理malloc/free和new/delete的区别new / opera new / 构造函数 之间的关系定位new表达式(placement-new)内存泄漏内存泄漏分类如何对待内存泄漏 new 和 delet 概念 new和delete是用于动态内存管理的运算符&am…...

Net6.0或Net7.0项目升级到Net8.0 并 消除.Net8中SqlSugar的警告

本文基于NetCore3.1或Net6.0项目升级到Net7.0&#xff0c;参考连接&#xff1a;NetCore3.1或Net6.0项目升级到Net7.0-CSDN博客 所有项目按照此步骤操作一遍&#xff0c;完成后再将所有引用的包&#xff08;即 *.dll&#xff09;更新升级到最新版&#xff08;注意&#xff1a;有…...

力扣题:字符串的反转-11.22

力扣题-11.22 [力扣刷题攻略] Re&#xff1a;从零开始的力扣刷题生活 力扣题1&#xff1a;541. 反转字符串 II 解题思想&#xff1a;进行遍历翻转即可 class Solution(object):def reverseStr(self, s, k):""":type s: str:type k: int:rtype: str"&quo…...

Effective C++(二):对象的初始化

文章目录 一、类的初始化二、全局静态对象的初始化 一、类的初始化 对于类中的成员变量的初始化&#xff0c;一般有两种方法&#xff0c;一种是在类中定义的时候直接赋予初值&#xff1a; class CTextBlock { private:std::size_t textLength{ 0 };bool lenisValid{ false }:…...

云原生高级--shell自动化脚本备份

shell自动化脚本实战---备份 数据库备份&#xff1a; 结合计划任务 MySQL、 Oracle 网站备份&#xff1a; tar&#xff0c;异地保存--ftp、rsync 一、数据库备份 1.利用自带工具mysqldump 实现数据库分库备份 分库备份&#xff1a; 1> 如何获取备份的…...

Spring Boot实现热部署

Spring Boot提供了一个名为spring-boot-devtools的开发工具&#xff0c;它可以实现热部署功能。通过使用spring-boot-devtools&#xff0c;可以在修改了resources目录下的内容后&#xff0c;自动重新加载应用程序&#xff0c;而无需手动重启。 以下是使用spring-boot-devtools…...

MVCC-

文章目录 1. 什么是MVCC2. 快照读和当前读3. 复习4. MVCC实现原理之ReadView5. 总结 文章目录 1. 什么是MVCC2. 快照读和当前读3. 复习4. MVCC实现原理之ReadView5. 总结 1. 什么是MVCC 口述&#xff1a;MVCC其实他是解决这种读-写的情况的&#xff0c;当然读-写也可以用 锁来…...

键盘打字盲打练习系列之刻意练习——1

一.欢迎来到我的酒馆 盲打&#xff0c;刻意练习! 目录 一.欢迎来到我的酒馆二.选择一款工具三.刻意练习第一步&#xff1a;基准键位练习第二步&#xff1a;字母键位练习第三步&#xff1a;数字符号键位练习 四.矫正坐姿 二.选择一款工具 工欲善其事必先利其器。在开始之前&…...

某公司前端笔试题(12.30)

1、对象数组去重&#xff1a; 数组去重&#xff1a; const a[{a:1,b:2},{a:2},{a:2},{a:1,c:3},{b:2,a:1}] 结果&#xff1a;[{a:1,b:2},{a:2},{a:1,c:3}] // 判断两个对象的属性值是否一致 const a [{ a: 1, b: 2 }, { a: 2 }, { a: 2 }, { a: 1, c: 3 }, { b: 2, a: 1 }] co…...

Sentinel核心类解读:Node

基本介绍 Sentinel中的簇点链路是由一个个的Node组成的&#xff0c;Node是一个接口。Node中保存了对资源的实时数据的统计&#xff0c;Sentinel中的限流或者降级等功能就是通过Node中的数据进行判断的。 Sentinel中是这样描述Node的&#xff1a; Holds real-time statistics…...

网络安全领域的12个大语言模型用例

网络安全是人工智能最大的细分市场&#xff0c;过去几年网络安全厂商纷纷宣称整合了人工智能技术&#xff08;当然也有很多仅仅是炒作&#xff09;&#xff0c;其中大部分是基于基线和统计异常的机器学习。 随着ChatGPT和类似生成式人工智能技术的飞速发展&#xff0c;基于大语…...

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…...

C++初阶-list的底层

目录 1.std::list实现的所有代码 2.list的简单介绍 2.1实现list的类 2.2_list_iterator的实现 2.2.1_list_iterator实现的原因和好处 2.2.2_list_iterator实现 2.3_list_node的实现 2.3.1. 避免递归的模板依赖 2.3.2. 内存布局一致性 2.3.3. 类型安全的替代方案 2.3.…...

React hook之useRef

React useRef 详解 useRef 是 React 提供的一个 Hook&#xff0c;用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途&#xff0c;下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...

ssc377d修改flash分区大小

1、flash的分区默认分配16M、 / # df -h Filesystem Size Used Available Use% Mounted on /dev/root 1.9M 1.9M 0 100% / /dev/mtdblock4 3.0M...

高等数学(下)题型笔记(八)空间解析几何与向量代数

目录 0 前言 1 向量的点乘 1.1 基本公式 1.2 例题 2 向量的叉乘 2.1 基础知识 2.2 例题 3 空间平面方程 3.1 基础知识 3.2 例题 4 空间直线方程 4.1 基础知识 4.2 例题 5 旋转曲面及其方程 5.1 基础知识 5.2 例题 6 空间曲面的法线与切平面 6.1 基础知识 6.2…...

leetcodeSQL解题:3564. 季节性销售分析

leetcodeSQL解题&#xff1a;3564. 季节性销售分析 题目&#xff1a; 表&#xff1a;sales ---------------------- | Column Name | Type | ---------------------- | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | -…...

在鸿蒙HarmonyOS 5中使用DevEco Studio实现录音机应用

1. 项目配置与权限设置 1.1 配置module.json5 {"module": {"requestPermissions": [{"name": "ohos.permission.MICROPHONE","reason": "录音需要麦克风权限"},{"name": "ohos.permission.WRITE…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)

UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中&#xff0c;UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化&#xf…...

QT: `long long` 类型转换为 `QString` 2025.6.5

在 Qt 中&#xff0c;将 long long 类型转换为 QString 可以通过以下两种常用方法实现&#xff1a; 方法 1&#xff1a;使用 QString::number() 直接调用 QString 的静态方法 number()&#xff0c;将数值转换为字符串&#xff1a; long long value 1234567890123456789LL; …...

NXP S32K146 T-Box 携手 SD NAND(贴片式TF卡):驱动汽车智能革新的黄金组合

在汽车智能化的汹涌浪潮中&#xff0c;车辆不再仅仅是传统的交通工具&#xff0c;而是逐步演变为高度智能的移动终端。这一转变的核心支撑&#xff0c;来自于车内关键技术的深度融合与协同创新。车载远程信息处理盒&#xff08;T-Box&#xff09;方案&#xff1a;NXP S32K146 与…...