简体   繁体   中英

Node JS App resulting in Too Many Connections on MySQL

This is how my code looks like:

var con = mysql.createPool({
        connectionLimit : 10,
      host: 'X.X.X.X',
      user: 'abcd',
      password: '1234',
      database: 'basic'
    });


con.query('INSERT INTO tbasic SET ?', data, (err, ret) => {
  if(err) {

      res.status(200).json({
          response_code:500,
          message:'Error inserting data!',
          data:err

      });
  }
  else {
      console.log('Last insert ID:', ret);

      res.status(200).json({
          response_code:200,
          message:'ok',
          data:ret

      });
  }


});

Whenever this application runs, after a while I get Too many connections error on the DB.

I know about the possible duplication issue but I have tried almost all solutions I found so far. None of them seems to work. What am I missing here?

Try using the long-handed way of pooling connections

var mysql = require('mysql');
var pool = mysql.createPool({
    connectionLimit : 10,
    host: 'X.X.X.X',
    user: 'abcd',
    password: '1234',
    database: 'basic'
});

pool.getConnection(function(err, connection) {
    if (err) throw err; // No connection

    connection.query('INSERT INTO tbasic SET ?', function(error, ret) {
        if(error) {
            res.status(200).json({
                response_code:500,
                message:'Error inserting data!',
                data:error

            });
        } else {
            console.log('Last insert ID:', ret);

            res.status(200).json({
                response_code:200,
                message:'ok',
                data:ret

            });
        }

        // Release current connection
        connection.release();
        // Handle error after connection released
        if (error) throw error;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM