node.js 全局连接已经存在。首先调用 sql.close()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44744946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js Global connection already exists. Call sql.close() first
提问by Laamiri Oussema
I'm trying to create web services using node.js from an sql server database,in the frontend when i call those 2 webservices simultaneously it throws an error Global connection already exists. Call sql.close() first .
我正在尝试使用来自 sql server 数据库的 node.js 创建 web 服务,在前端,当我同时调用这两个 web 服务时,它抛出一个错误全局连接已经存在。首先调用 sql.close() 。
Any Solution ?
任何解决方案?
var express = require('express');
var router = express.Router();
var sql = require("mssql");
router.get('/Plant/:server/:user/:password/:database', function(req, res, next) {
user = req.params.user;
password = req.params.password;
server = req.params.server;
database = req.params.database;
// config for your database
var config = {
user: user,
password: password,
server: server,
database:database
};
sql.connect(config, function (err) {
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("SELECT distinct PlantName FROM MachineryStateTable"
, function (err, recordset) {
if (err) console.log(err)
else {
for(i=0;i<recordset.recordsets.length;i++) {
res.send(recordset.recordsets[i])
}
}
sql.close();
});
});
});
router.get('/Dep/:server/:user/:password/:database/:plantname', function(req, res, next) {
user = req.params.user;
password = req.params.password;
server = req.params.server;
database = req.params.database;
plantname = req.params.plantname;
// config for your database
var config = {
user: user,
password: password,
server: server,
database:database
};
sql.connect(config, function (err) {
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("SELECT distinct DepName FROM MachineryStateTable where PlantName= '"+plantname+"'"
, function (err, recordset) {
if (err) console.log(err)
else {
for(i=0;i<recordset.recordsets.length;i++) {
res.send(recordset.recordsets[i])
}
sql.close();
}
});
});
});
module.exports = router;
回答by bams
You have to create a poolConnectiontry this:
你必须创建一个poolConnection试试这个:
new sql.ConnectionPool(config).connect().then(pool => {
return pool.request().query("SELECT * FROM MyTable")
}).then(result => {
let rows = result.recordset
res.setHeader('Access-Control-Allow-Origin', '*')
res.status(200).json(rows);
sql.close();
}).catch(err => {
res.status(500).send({ message: `${err}`})
sql.close();
});
回答by Shivam
From the documentation, close method should be used on the connection, and not on the required module,
从文档中,应该在连接上使用 close 方法,而不是在所需的模块上,
So should be used like
所以应该像这样使用
var connection = new sql.Connection({
user: '...',
password: '...',
server: 'localhost',
database: '...'
});
connection.close().
Also couple of suggestions,
1. putting res.send in a loop isn't a good idea, You could reply back the entire recordsets or do operations over it, store the resultant in a variable and send that back.
2. Try using promises, instead of callbacks, it would make the flow neater
还有一些建议,
1.将 res.send 放入循环中不是一个好主意,您可以回复整个记录集或对其进行操作,将结果存储在变量中并将其发送回去。
2. 尝试使用promises,而不是回调,它会使流程更整洁
回答by ehitel rodriguez castro
You must use ConnectionPool.
您必须使用连接池。
Next function returns a recordset with my query results.
Next 函数返回一个包含我的查询结果的记录集。
async function execute2(query) {
return new Promise((resolve, reject) => {
new sql.ConnectionPool(dbConfig).connect().then(pool => {
return pool.request().query(query)
}).then(result => {
resolve(result.recordset);
sql.close();
}).catch(err => {
reject(err)
sql.close();
});
});
}
Works fine in my code!
在我的代码中运行良好!
回答by Mohammed Sabbir
if this problem still bother you, then change the core api. go to node_modules\mssql\lib\base.js at line 1723, add below code before if condition globalConnection = null
如果这个问题仍然困扰你,那么改变核心api。转到第 1723 行的 node_modules\mssql\lib\base.js,如果条件 globalConnection = null 在之前添加以下代码
回答by Jason Goemaat
Don't read their documentation, I don't think it was written by someone that actually uses the library :) Also don't pay any attention to the names of things, a 'ConnectionPool' doesn't seem to actually be a connection pool of any sort. If you try and create more than one connection from a pool, you will get an error. This is the code that I eventually got working:
不要阅读他们的文档,我认为它不是由实际使用该库的人编写的 :) 也不要注意事物的名称,“ConnectionPool”似乎实际上并不是一个连接任何类型的池。如果您尝试从池中创建多个连接,您将收到错误消息。这是我最终开始工作的代码:
const sql = require('mssql');
let pool = new sql.ConnectionPool(config); // some object that lets you connect ONCE
let cnn = await pool.connect(); // create single allowed connection on this 'pool'
let result = await cnn.request().query(query);
console.log('result:', result);
cnn.close(); // close your connection
return result;
This code can be run multiple times in parallel and seems to create multiple connections and correctly close them.
此代码可以并行运行多次,似乎创建了多个连接并正确关闭它们。
回答by Jared
In case someone comes here trying to find out how to use SQL Server pool connection with parameters:
如果有人来这里试图找出如何使用带参数的 SQL Server 池连接:
var executeQuery = function(res,query,parameters){
new sql.ConnectionPool(sqlConfig).connect().then(pool =>{
// create request object
var request = new sql.Request(pool);
// Add parameters
parameters.forEach(function(p) {
request.input(p.name, p.sqltype, p.value);
});
// query to the database
request.query(query,function(err,result){
res.send(result);
sql.close();
});
})
}

