通過 SQL 連線。mssql npm 模組

我們將首先建立一個具有基本結構的簡單節點應用程式,然後連線本地 sql server 資料庫並對該資料庫執行一些查詢。

步驟 1: 根據你要建立的專案名稱建立目錄/資料夾。使用 npm init 命令初始化節點應用程式,該命令將在當前目錄中建立 package.json。

mkdir mySqlApp
//folder created 
cd mwSqlApp
//change to newly created directory
npm init
//answer all the question ..
npm install
//This will complete quickly since we have not added any packages to our app.

第 2 步: 現在我們將在此目錄中建立一個 App.js 檔案,並安裝一些我們將需要連線到 sql db 的軟體包。

sudo gedit App.js
//This will create App.js file , you can use your fav. text editor :)
npm install --save mssql
//This will install the mssql package to you app

第 3 步: 現在我們將向我們的應用程式新增一個基本配置變數,mssql 模組將使用它來建立連線。

console.log("Hello world, This is an app to connect to sql server.");
var config = {
        "user": "myusername", //default is sa
        "password": "yourStrong(!)Password",
        "server": "localhost", // for local machine
        "database": "staging", // name of database
        "options": {
            "encrypt": true
        }
      }

sql.connect(config, err => { 
    if(err){
        throw err ;
    }
    console.log("Connection Successful !");

    new sql.Request().query('select 1 as number', (err, result) => {
        //handle err
        console.dir(result)
        // This example uses callbacks strategy for getting results.
    })
        
});

sql.on('error', err => {
    // ... error handler 
    console.log("Sql database connection error " ,err);
})

第 4 步: 這是最簡單的步驟,我們啟動應用程式,應用程式將連線到 sql server 並列印出一些簡單的結果。

node App.js
// Output : 
// Hello world, This is an app to connect to sql server.
// Connection Successful !
// 1

要使用 promises 或 async 執行查詢,請參閱 mssql 包的官方文件: