2017-08-25 102 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(); 
    });