node.js Global connection already exists. Call sql.close() first
You have to create a poolConnection
try this:
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(); });
From the documentation, close method should be used on the connection, and not on the required module,
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
You must use ConnectionPool.
Next function returns a recordset with my query results.
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!