mysql icon indicating copy to clipboard operation
mysql copied to clipboard

PROTOCOL_CONNECTION_LOST

Open lcherukuri opened this issue 10 years ago • 3 comments

I used below error handling code for connection timeout. Still i face the problem. Did any one faced this problem

var config = require('../config/config');

    module.exports = function(){

        var mysql      = require('mysql');
        var db_config = {
            host     : config.db_host,
            user     : config.db_username,
            password : config.db_password,
            database : config.db_name
        };

        var connection;

        function handleDisconnect() {
              connection = mysql.createConnection(db_config); // Recreate the connection, since

              connection.connect(function(err) {              
                if(err) {                                    
                  console.log('error when connecting to db:', err);
                  setTimeout(handleDisconnect, 2000); 
                }                                   
              });                                   

              connection.on('error', function(err) {
                console.log('db error', err);
                if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
                  handleDisconnect();                        
                } else {                                     
                  throw err;                                 
                }
              });
            }

            handleDisconnect();

        return connection;

    }

lcherukuri avatar Feb 18 '16 03:02 lcherukuri

Just try delete connection.connect method. It's interesting but working for me and it doesn't make another connection to mysql.

centrual avatar Feb 18 '16 04:02 centrual

Similar? #1334

czioutas avatar Feb 18 '16 08:02 czioutas

Hi @lc4377, that code will not actually work when given through module.exports, since the originally-exported connection object will never actually be changed (this is how references work in the JavaScript language).

If you want to keep a connection open for a long time, you need to refactor your code to use connection pooling (https://github.com/felixge/node-mysql#pooling-connections) instead of trying to keep a single connection open forever.

dougwilson avatar Feb 18 '16 19:02 dougwilson