1

I connected mysql to nodejs. After a certain period of time, you will get the error :

'Connection lost the server closed the connection'.

I need your help.

An error has occurred and we added the function handleDisconnect. However, once a disconnect is resolved, the second error occurs again from Connection lost the server closed the connection.

I wonder why it should be only once and not the second one.

ps: The description may not be smooth using a translator.

This is part of the app.js file

// connection to databases
var mysql_dbc = require('./config/db_con')();
var connection = mysql_dbc.init();
mysql_dbc.test_open(connection);

// Added Code
handleDisconnect(connection);
function handleDisconnect(client) {

  client.on('error', function (error) {

    if (!error.fatal) return;

    if (error.code !== 'PROTOCOL_CONNECTION_LOST') throw err;

    console.error('> Re-connecting lost MySQL connection: ' + error.stack);

    mysql_dbc.test_open(connection);

  });

};

1 Answer 1

2

You can try to use this code to handle server disconnect:

var mysql = require("mysql");
var configuration = {
  host: "localhost",
  user: "root",
  password: "mysql",
  database: "blog"
};
var connection;

function handleDisconnect() {
  connection = mysql.createConnection(configuration);

  connection.connect(function(err) {
    if (err) {
      console.log("error when connecting to db:", err);
      setTimeout(handleDisconnect, 2000);
    }else{
        console.log("connection is successfull");
    }
  });
  connection.on("error", function(err) {
    console.log("db error", err);
    if (err.code === "PROTOCOL_CONNECTION_LOST") {
      handleDisconnect();
    } else {
      throw err;
    }
  });
}
handleDisconnect();

You may lose the connection to a MySQL server due to network problems, the server timing you out, the server being restarted, or crashing. All of these events are considered fatal errors.

Re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your first response. I get an error in this part. Did you have a typo? if(err) { sometimes).
yes, sorry removed it. you can check it now. it sould work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.