我遇到需要查询多个SQL Server以获取大量数据的情况。所以,我首先迭代SQL Server,然后迭代必须运行的查询。在我的调用函数中,我有以下代码
config.servers.forEach((element) => {
sqlServer = element.server;
element.queries.forEach(function(configQuery) {
jsonKey = configQuery.key;
sqlQuery = configQuery.query
sqlDatabase = configQuery.database;
var out;
if (configQuery.parameter) {
sqlQuery = sqlQuery + " WHERE " + configQuery.parameter + " = '" + partNumber + "'";
}
sqlHelper.sqlFun(sqlQuery, sqlServer, sqlDatabase, jsonKey, callback)
})
sqlFun引用了以下函数
let connection ;
function poolIt (sqlQuery,sqlServer,databaseName) {
if(!connection)
{
//sqlServer_temp = sqlServer
//instead of checking if connection is defined
//we have to check if connection is open
var dbConfiguration = {
driver: 'msnodesqlv8',
server: sqlServer,
database: databaseName,
options: {
trustedConnection: true
}
}
connection = sql.connect(dbConfiguration);
}
}
function runQuery(sqlQuery,sqlServer,databaseName,sqlKey, callback) {
poolIt(sqlQuery,sqlServer,databaseName)
connection.then(pool =>{
return pool.request().query(sqlQuery)
}).then(result=>{
if(callback)
return callback(null,result.recordset, sqlKey )
}).catch(err=>{
if(callback)
{
console.log(err)
return callback(err,null, sqlKey)
}
})
}
module.exports.sqlFun = runQuery;
我面临的问题是,对于我尝试建立的所有SQL Server连接,所有连接到同一个SQL Server。我明白它是由于函数poolIt,因为我在那里检查是否存在连接,如果它存在,我只是走出循环。我想知道在我使用第一个SQL Server进行迭代后执行查询时如何关闭此连接?我试过sql.close()和connection.close(),但它们无法正常工作。如果我使用它,该程序会挂起很长时间。