国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

前端使用node.js連接sql.server數(shù)據(jù)庫教程

這篇具有很好參考價值的文章主要介紹了前端使用node.js連接sql.server數(shù)據(jù)庫教程。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

最近項目中要用到node寫接口然后連接公司現(xiàn)有的sql.server數(shù)據(jù)庫,再把執(zhí)行結(jié)果返回給前端(還是我),因為之前一直做前端這塊,后端這方面不是很懂,花了很長的時間終于研究出來了(還是太菜了,走了很多彎路),所以寫個博客,一是復(fù)習(xí)鞏固,二是給其他有需要的小伙伴一個參考,盡量少走彎路,廢話不多說,直接上代碼

1.首先在自己的數(shù)據(jù)庫新建一張表,用于接下來的測試

前端使用node.js連接sql.server數(shù)據(jù)庫教程

?2.在自己的項目文件夾中建兩個文件,config.js & mssql.js

3.封裝數(shù)據(jù)庫信息,config.js

//config.js
let app = {
    user: 'xxxxxx', //這里寫你的數(shù)據(jù)庫的用戶名
    password: 'xxxxxx',//這里寫數(shù)據(jù)庫的密碼
    server: 'localhost', 
    database: 'testDB', // 數(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

4.對sql語句的二次封裝 , mssql.js

//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;

5.接口代碼,api/user.js

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

/* GET home page. */
router.get('/info', function (req, res, next) {
    db.selectAll('userInfo', function (err, result) {//查詢所有userInfo表的數(shù)據(jù)
        res.send(result.recordset)
        // res.render('userInfo', { results: result.recordset, moment: moment });
    });
});
router.post('/delete', function (req, res, next) {//刪除一條id對應(yīng)的userInfo表的數(shù)據(jù)
    console.log(req.body, 77);
    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;

6.啟動文件,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')
})

7.啟動服務(wù)器

前端使用node.js連接sql.server數(shù)據(jù)庫教程

8.用postman測試接口

前端使用node.js連接sql.server數(shù)據(jù)庫教程

前端使用node.js連接sql.server數(shù)據(jù)庫教程

?

?數(shù)據(jù)成功返回~~~文章來源地址http://www.zghlxwxcb.cn/news/detail-505858.html

到了這里,關(guān)于前端使用node.js連接sql.server數(shù)據(jù)庫教程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 解決idea [08S01] 無法連接 sql server 數(shù)據(jù)庫,報錯:驅(qū)動程序無法通過使用安全套接字層(SSL)加密與 SQL Server 建立安全連接

    因為sql server在jdbc連接的時候需要一定的安全驗證,只需要在dbURL中把;trustServerCertificate=true加上后令其跳過就行了 上面的代碼報錯如下: 在dbURL中把;trustServerCertificate=true加上后就沒有報錯了 無報錯 因為sql server在jdbc連接的時候需要一定的安全驗證, 只需要在dbURL中把;trustS

    2024年03月23日
    瀏覽(30)
  • VsCode連接Mysql、Redis、MariaDB、SQL Server等數(shù)據(jù)庫并進行可視化操作。無需額外的去下載可視化數(shù)據(jù)軟件了,VsCode前端很方便的插件?。。? decoding=

    VsCode連接Mysql、Redis、MariaDB、SQL Server等數(shù)據(jù)庫并進行可視化操作。無需額外的去下載可視化數(shù)據(jù)軟件了,VsCode前端很方便的插件?。?!

    前言:VsCode直接連接并操作數(shù)據(jù)庫!最近使用公司的新電腦時,才發(fā)現(xiàn)好多東西需要重新下載 、配置,最近偶然接觸到了 VsCode 的 Database Clinent 插件,可連接眾多的服務(wù),其中就支持連接到本地和遠程的數(shù)據(jù)庫,可視化操作、語句查詢、導(dǎo)入、導(dǎo)出數(shù)據(jù)等基本功能集合,個人

    2024年02月05日
    瀏覽(29)
  • 問題解決:idea 中無法連接 sql server 數(shù)據(jù)庫,報錯 [08S01] 驅(qū)動程序無法通過使用安全套接字層(SSL)加密與 SQL Server 建立安全連接

    問題解決:idea 中無法連接 sql server 數(shù)據(jù)庫,報錯 [08S01] 驅(qū)動程序無法通過使用安全套接字層(SSL)加密與 SQL Server 建立安全連接

    報的錯誤信息如下: [08S01] 驅(qū)動程序無法通過使用安全套接字層(SSL)加密與 SQL Server 建立安全連接。錯誤:“PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target”。 ClientConnectionId:721941c7-3e08-4e80-bc56-418e1c051624 sun.securi

    2024年02月12日
    瀏覽(26)
  • 使用asp.net core web api創(chuàng)建web后臺,并連接和使用Sql Server數(shù)據(jù)庫

    使用asp.net core web api創(chuàng)建web后臺,并連接和使用Sql Server數(shù)據(jù)庫

    前言:因為要寫一個安卓端app,實現(xiàn)從服務(wù)器中獲取電影數(shù)據(jù),所以需要搭建服務(wù)端代碼,之前學(xué)過C#,所以想用C#實現(xiàn)服務(wù)器段代碼用于測試,本文使用C#語言,使用asp.net core web api組件搭建服務(wù)器端,并訪問sql server 數(shù)據(jù)庫。 一、安裝Visual studio 2022 社區(qū)版,并安裝ASP.NET和

    2024年02月14日
    瀏覽(28)
  • node.js之連接數(shù)據(jù)庫

    node.js之連接數(shù)據(jù)庫

    我們?nèi)绾卧趎odejs中連接并操作數(shù)據(jù)庫呢? 讓我為大家解答一下吧! 1.安裝操作MySQL數(shù)據(jù)庫的第三方塊 (mysql) mysql 模塊是托管于 npm 上的第三方塊。它提供了在 Nodejs 項目中連接和操作 MySQL 數(shù)據(jù)庫的能力想要在項目中使用它,需要先運行如下命令,將mysql安裝為項目的依賴包 2

    2024年01月19日
    瀏覽(36)
  • Node.js 連接 mysql 數(shù)據(jù)庫

    目錄 一、安裝驅(qū)動 二、連接數(shù)據(jù)庫 1、數(shù)據(jù)庫連接的配置信息 數(shù)據(jù)庫連接參數(shù)說明 2、封裝 mysql 的執(zhí)行語句 3、后端路由文件? 三、數(shù)據(jù)庫操作( CURD ) 1、查詢數(shù)據(jù) 2、插入數(shù)據(jù) 3、更新數(shù)據(jù) 4、刪除數(shù)據(jù) 4、獲取受影響的行數(shù) 5、獲取更改的行數(shù) 6、多語句查詢 7、事務(wù) 四、E

    2024年02月07日
    瀏覽(23)
  • VS連接SQL server數(shù)據(jù)庫

    VS連接SQL server數(shù)據(jù)庫

    目錄 連接數(shù)據(jù)庫 使用dataGridView控件顯示表中的數(shù)據(jù)。 實現(xiàn)基本CRUD操作 打開vs,點擊 視圖,打開sql資源管理器,添加SQL Server 輸入服務(wù)器名稱,用戶名,密碼,進行連接。 如圖,就可以看到vs已經(jīng)連接到了自己的數(shù)據(jù)庫,class和song兩個數(shù)據(jù)庫 ??梢钥吹絚lass下面有五個表。

    2024年02月09日
    瀏覽(17)
  • Sql server 連接 Oracle數(shù)據(jù)庫

    Sql server 連接 Oracle數(shù)據(jù)庫

    前提預(yù)警:本機必須裝有Oracle客戶端 檢查是否安裝Oracle客戶端,并檢查TNS信息是否配置完成 1.1、 在cmd中執(zhí)行 sqlplus ,沒有報錯并出現(xiàn)Oracle版本號,則表示Oracle已安裝 1.2、配置TNS信息(最上面的10.0.0.130可隨意定義,eg:test、orcl、qerghasd…) 配置ODBC數(shù)據(jù)信息 2.1、打開ODBC數(shù)據(jù)

    2024年02月03日
    瀏覽(20)
  • Navicat連接SQL Server數(shù)據(jù)庫

    使用navicat連接sqlserver數(shù)據(jù)庫時必須連接sqlserver驅(qū)動,否則的話會連接報錯; 按照應(yīng)用的常理來說都是高版本兼容低版本的驅(qū)動; 我這邊呢,是一個SQL Server Native Client 11.0的驅(qū)動; 大家需要的話可以到SQL Server官網(wǎng)網(wǎng)址去下載各類驅(qū)動; 網(wǎng)址:https://docs.microsoft.com/en-us/sql/con

    2024年02月08日
    瀏覽(25)
  • 【SQL Server】無需公網(wǎng)IP,就可以遠程連接SQL Server數(shù)據(jù)庫

    【SQL Server】無需公網(wǎng)IP,就可以遠程連接SQL Server數(shù)據(jù)庫

    目錄 1.前言 2.本地安裝和設(shè)置SQL Server 2.1 SQL Server下載 2.2 SQL Server本地連接測試 2.3 Cpolar內(nèi)網(wǎng)穿透的下載和安裝 2.3 Cpolar內(nèi)網(wǎng)穿透的注冊 3.本地網(wǎng)頁發(fā)布 3.1 Cpolar云端設(shè)置 3.2 Cpolar本地設(shè)置 4.公網(wǎng)訪問測試 5.結(jié)語 數(shù)據(jù)庫的重要性相信大家都有所了解,作為各種數(shù)據(jù)的電子資料夾,

    2023年04月24日
    瀏覽(26)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包