我已經連接MSSQL使用下面的代碼全球連接已存在問題的node.js
var sql = require('mssql')
var config ={
server:'xxxx',
database:'xxxx',
user:'xxx',
password:'xxx',
port:'xx'
};
sql.connect(dbconfig, function (err) {
if (err) console.log(err);
var sqlquery='';
const request = new sql.Request();
if(condition)
{
//query to the database and get the repo value
sqlquery='select * from verylargetable';
request.query(sqlquery, function (err, result) {
if (err) console.log(err)
var repo=result.recordset[0].Repo;
//query to the database and get the comm value
sqlquery="select commit from verylargetable where Repo='"+repo+"'";
request.query(sqlquery, function (err, result) {
if (err) console.log(err)
var comm=result.recordset[0].Comm;
if (result.recordset.length > 0)
{
//query to the database and update the table
sqlquery="UPDATE verylargetable set Repo='"+repo+"', WHERE Comm='"+comm+"'";
request.query(sqlquery, function (err,result){
if (err) console.log(err)
console.log("record(s) updated");
});
}
});
});
}
else
{
//query to the database and get the repo value
sqlquery='select * from verylargetable';
request.query(sqlquery, function (err, result) {
if (err) console.log(err)
var repo=result.recordset[0].Repo;
//query to the databaseto insert new record
sqlquery ="INSERT INTO verylargetable VALUES("+repo+"','"+comm+"',1)";
request.query(sqlquery, function (err, result) {
if (err) console.log(err)
});
});
}
});
的node.js基於某些條件必須執行查詢。在執行時,這些查詢會被正確更新。但有時會遇到以下問題
全局連接已經存在。首先調用sql.close()。
當我在最後使用sql.close()時,我無法下次初始化連接。
面向連接關閉問題。
我有單獨的數據庫更改方法。我需要在方法開始時建立連接,並且必須在最後關閉。在兩者之間必須執行所有查詢。 請讓我知道如何正確打開和關閉連接?
可能有[錯誤:全局連接已存在。調用sql.close()第一](https://stackoverflow.com/questions/43345149/error-global-connection-already-exists-call-sql-close-first) –
https://stackoverflow.com/questions/ 43345149/error-global-connection-already-exists-call-sql-close-first –
你試過用下面的解決方案嗎? –