Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys I have an error on mssql with node.js, the code below performs a select on a Sql Server 2014 database and insert the data into an array! My problem is that in some cases this error occurs:

Global connection already exists. Call sql.close() first.


How can I resolve this error?


What I have tried:

This is my code!

JavaScript
const DbConfig = require('../Config/DatabaseConfig.js');
const sql = require('mssql');

async function RicercaCantiere(NomeCantiere) {
	var data=[];
	await sql.connect(DbConfig.config);
	const request = new sql.Request();
    request.input('NomeCantiere', sql.VarChar, NomeCantiere);
	const recordset=await request.query("select * from CantiereConsuntivo where NomeCantiere like '%' + @NomeCantiere +'%' ");
	for(var i=0; i<recordset.recordset.length; i++){     
		data.push({
			IdCantiere: recordset.recordset[i].IdCantiere, 
			IdCliente: recordset.recordset[i].IdCliente,
			Filiale: recordset.recordset[i].Filiale,
			RagioneSociale: recordset.recordset[i].RagioneSociale,
			NomeCantiere: recordset.recordset[i].NomeCantiere,
			DataCreazioneCantiere: recordset.recordset[i].DataCreazioneCantiere,
			Tipologia: recordset.recordset[i].Tipologia,
			StatoCantiere: recordset.recordset[i].StatoCantiere,
			StatoFatturazione: recordset.recordset[i].StatoFatturazione
	  })
	}
	await sql.close();
	return data;
}

module.exports.RicercaCantiere = RicercaCantiere;
Posted
Updated 10-Apr-18 22:25pm
v4
Comments
Kornfeld Eliyahu Peter 11-Apr-18 4:26am    
As you are working async, you can hit sql.connect a second time before sql.close reached...
You should consider to move connect and close to a global level...
rikidev 11-Apr-18 4:31am    
I was thinking about it! But I have no idea how to organize it to guarantee mutual exclusion at this method!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900