w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
nodejs mysql Error: Connection lost The server closed the connection

Try to use this code to handle server disconnect:

var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'

var connection;

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

  connection.connect(function(err) {              // The server is either
    if(err) {                                     // or restarting (takes a
while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before
attempting to reconnect,
    }                                     // to avoid a hot loop, and to
allow our node script to
  });                                     // process asynchronous requests
in the meantime.
                                          // If you're also serving http,
display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the
MySQL server is usually
      handleDisconnect();                         // lost due to either
server restart, or a
    } else {                                      // connnection idle
timeout (the wait_timeout
      throw err;                                  // server variable
configures this)


In your code i am missing the parts after connection = mysql.createConnection(db_config);

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.