最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

node.js連接SQLserver數(shù)據(jù)庫實踐

 更新時間:2026年03月27日 09:12:25   作者:小沐°  
這篇文章主要介紹了node.js連接SQLserver數(shù)據(jù)庫實踐方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

1.在自己的項目JS文件夾中建文件

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

2.在config.js中封裝數(shù)據(jù)庫信息

let app = {
  user: 'sa', //這里寫你的數(shù)據(jù)庫的用戶名
  password: '',//這里寫數(shù)據(jù)庫的密碼
  server: 'localhost',
  database: 'medicineSystem', // 數(shù)據(jù)庫名字
  port: 1433, //端口號,默認1433
  options: {
    encrypt: false,  //加密,設(shè)置為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 參數(shù),用來解釋sql中的@*,例如: { id: id }
 * @param callBack 回調(diào)函數(shù)
 */
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 數(shù)據(jù)庫表名,例:'news'
 * @param topNumber 只查詢前幾個數(shù)據(jù),可為空,為空表示查詢所有
 * @param whereSql 條件語句,例:'where id = @id'
 * @param params 參數(shù),用來解釋sql中的@*,例如: { id: id }
 * @param orderSql 排序語句,例:'order by created_date'
 * @param callBack 回調(diào)函數(shù)
 */
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)
  }
};

/**
 * 查詢指定表的所有數(shù)據(jù)
 * @param tableName 數(shù)據(jù)庫表名
 * @param callBack 回調(diào)函數(shù)
 */
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 數(shù)據(jù)庫表名
 * @param callBack 回調(diào)函數(shù)
 */
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)
  }
};

/**
 * 更新指定表的數(shù)據(jù)
 * @param updateObj 需要更新的對象字段,例:{ name: 'name', age: 20 }
 * @param whereObj 需要更新的條件,例: { id: id }
 * @param tableName 數(shù)據(jù)庫表名
 * @param callBack 回調(diào)函數(shù)
 */
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 參數(shù),用來解釋sql中的@*,例如: { id: id }
 * @param tableName 數(shù)據(jù)庫表名
 * @param callBack 回調(diào)函數(shù)
 */
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) {//查詢某表下的全部數(shù)據(jù)
  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對應(yīng)的userInfo表的數(shù)據(jù)
  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) {//更新一條對應(yīng)id的userInfo表的數(shù)據(jù)
  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.導(dǎo)入模塊
const express = require('express')

//2.創(chuàng)建服務(wù)器
let server = express()
server.use(express.urlencoded()) //中間件要寫在啟動文件里面

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

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

server.use('/', user)

//3.開啟服務(wù)器
server.listen(8002, () => {
  console.log('服務(wù)器已啟動,在端口號8002')
})

6.啟動服務(wù)器

cmd到server.js所在的目錄下輸入:

nodemon server.js

7.用postman測試接口

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

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

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

    這篇文章主要介紹了node.js中的events.EventEmitter.listenerCount方法使用說明,本文介紹了events.EventEmitter.listenerCount的方法說明、語法、使用實例和實現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • Nest.js散列與加密實例詳解

    Nest.js散列與加密實例詳解

    這篇文章主要給大家介紹了關(guān)于Nest.js散列與加密的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • Node.js中用D3.js的方法示例

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

    這篇文章主要給大家介紹了在Node.js中用D3.js的方法,文中分別介紹了如何安裝模塊和一小段簡單的示例代碼,有需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-01-01
  • node.js 使用 net 模塊模擬 websocket 握手進行數(shù)據(jù)傳遞操作示例

    node.js 使用 net 模塊模擬 websocket 握手進行數(shù)據(jù)傳遞操作示例

    這篇文章主要介紹了node.js 使用 net 模塊模擬 websocket 握手進行數(shù)據(jù)傳遞操作,結(jié)合實例形式分析了node.js基于net模塊模擬 websocket握手相關(guān)原理及進行數(shù)據(jù)傳遞具體操作技巧,需要的朋友可以參考下
    2020-02-02
  • npm 常用命令詳解(小結(jié))

    npm 常用命令詳解(小結(jié))

    這篇文章主要介紹了npm 常用命令詳解(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • 詳解如何修改 node_modules 里的文件

    詳解如何修改 node_modules 里的文件

    這篇文章主要介紹了詳解如何修改node_modules里的文件,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • 詳解Node.js開發(fā)中的express-session

    詳解Node.js開發(fā)中的express-session

    express-session?是基于express框?qū)iT用于處理session的中間件,本篇文章主要介紹了詳解Node.js開發(fā)中的express-session,有興趣的可以了解一下<BR>
    2017-05-05
  • Node中fs文件系統(tǒng)模塊的使用方法詳解

    Node中fs文件系統(tǒng)模塊的使用方法詳解

    fs?模塊是?Node.js?官方提供的、用來操作文件的模塊(內(nèi)置api),它提供了一系列的方法和屬性,用來滿足用戶對文件的操作需求,本文給大家介紹了Node中fs文件系統(tǒng)模塊的使用方法,需要的朋友可以參考下
    2024-03-03
  • 為什么Node.js會這么火呢?Node.js流行的原因

    為什么Node.js會這么火呢?Node.js流行的原因

    是什么原因讓Node.js突然間如此流行呢?聽起來像是有了一種新的Web開發(fā)技術(shù),是這樣嗎?我們來匯總一下。
    2014-12-12
  • node.js實現(xiàn)學(xué)生檔案管理

    node.js實現(xiàn)學(xué)生檔案管理

    這篇文章主要為大家詳細介紹了node.js實現(xiàn)學(xué)生檔案管理,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05

最新評論

云霄县| 武邑县| 北碚区| 锡林郭勒盟| 连云港市| 德昌县| 通海县| 天水市| 泸州市| 广州市| 锦州市| 鹤峰县| 博乐市| 海盐县| 儋州市| 葵青区| 南开区| 宁国市| 长乐市| 阿鲁科尔沁旗| 进贤县| 祥云县| 怀仁县| 武乡县| 景德镇市| 延长县| 水富县| 苍梧县| 三台县| 柘城县| 调兵山市| 五莲县| 洪洞县| 松滋市| 抚州市| 多伦县| 那曲县| 开封县| 同仁县| 澳门| 汝州市|