2017-08-25 58 views
2

我使用NodeJS連接SQL Server。我的初始代碼是:NodeJS和SQL Server連接錯誤

const poolA = new sql.ConnectionPool(config, err => { 
     poolA.request() 
      .query("select * from AnyTable", function(err, result) { 
       if (err) 
        message = "Error!"; 
       else {       
        //Do something else 
        message = "Done!"; 
       } 
      }) 
    }); 

我得到了「connection s closed error」。我收錄了

poolA.close() 

而且它也沒有解決問題。

我把它改爲:

new sql.ConnectionPool(config).then(pool => { 
     pool.request() 
      .query("select * from AnyTable") 
    }).then(result => { 
     //Do something else 
     message = "Done!"; 
     sql.close(); 
    }).catch(err => { 
     message = "Error!"; 
     sql.close(); 
    }); 

,現在我得到的「那麼是不是一個函數」的錯誤。

什麼是正確的方式:

  1. 創建一個連接,如果不存在
  2. 如果連接已經存在它,使用它

我收到各種錯誤的。有人可以幫我解決這個問題嗎?

回答

1

如果您使用的節點,那麼你應該使用的承諾,正如你在第二個選項一樣。所以正確的做法應該如下 -

sql.close() 
    sql.connect(sqlConfig).then(pool => { 
    pool.request() 
    .input('param1', sql.Int, valueParam1) 
    .input('param2', sql.Int, valueParam2) 
    .execute(procedureToExecute).then(result => { 
     // Do whatever you want with the result. 
}) 

請記住,鏈接只有在您從諾言中返回任何東西時纔有可能。在你的情況下,你沒有返回連接池或承諾中的任何內容,因此".then is not a function" error.因此,如果你想再次使用池,或者想要使用結果時返回結果,你應該返回池。

第二個更好的選擇是創建連接一次,然後在任何地方使用它。這個概念非常類似於MongoDB ConnectionPooling的概念,請檢查它的細節。對於此創建一個db.js文件,如下 -

'use strict' 

const config = require(__dirname + '/index.js') 
, mssql = require('mssql') 
, sqlConfig = { 
, user: config.databaseUsername 
, password: config.databasePassword 
, server: config.databaseHost 
, database: config.database.database 
pool: { 
    max: 10, 
    min: 0, 
    idleTimeoutMillis: 30000 
    } 
} 

let connection = mssql.connect(sqlConfig,err => { 
    if (err) 
    {throw err} 
}) 

module.exports = connection 

然後線(需要),您要使用下面的連接在服務器上的文件或任何模塊上面 -

db = require(process.cwd() + '/config/db.js') 

可以包括這在請求選項如下 -

let options = {db:db} 
request.options = options 

希望這可以幫助,讓我知道,以防您需要任何幫助。

0

我沒有測試它,但看你的代碼,你不返回任何承諾第二則(),所以你會碰到這個錯誤。那麼是不是一個功能

嘗試增加在第一一個回報則()

new sql 
    .ConnectionPool(config) 
    .then(pool => { 
     return pool 
     .request() 
     .query("select * from AnyTable") 
    }) 
    .then(result => { 
     //Do something else 
     message = "Done!"; 
     sql.close(); 
    }) 
    .catch(err => { 
     message = "Error!"; 
     sql.close(); 
    });