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

前端 未结 6 1570
暗喜
暗喜 2021-01-03 23:09

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 connect

相关标签:
6条回答
  • 2021-01-03 23:50

    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:

    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.

    0 讨论(0)
  • 2021-01-03 23:59

    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

    0 讨论(0)
  • 2021-01-04 00:00

    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

    0 讨论(0)
  • 2021-01-04 00:12

    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();
    
      });
    
    0 讨论(0)
  • 2021-01-04 00:12

    In case someone comes here trying to find out how to use SQL Server pool connection with parameters:

    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();
    
        });
     })       
    } 
    
    0 讨论(0)
  • 2021-01-04 00:14

    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!

    0 讨论(0)
提交回复
热议问题