John
John

Reputation: 41

Is there a way to fix the mysql reconnection issue in node.js?

Hello when making calls to the mysql server if the connection is not open/disconnected due to a long time of not using it then it will give me an error when I attempt to Re-Connect. I have looked this error up but the responses don't seem to help me in my situation. Here is the error: Cannot enqueue Handshake after already enqueuing a Handshake. Here is the code causing this:

var con = mysql.createConnection({
    host: "",
    user: "",
    password: "",
    database: ""
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
});

con.on('error', function(err) {
    console.log(err);
    console.log('MYSQL Disconnected');
})

if (con.state == 'disconnected') {
    con.connect(function(err) {
        if (err) throw err;
    });
}

More code is below but is irrelevant due to it checking for authenticated state and querying

Upvotes: 2

Views: 1088

Answers (1)

FanoFN
FanoFN

Reputation: 7124

The difference I found between mysql.createConnection and mysql.createPool is when the former lost connection to MySQL (timeout), I need to restart the node server to re-establish connection. With create pool, the app only uses mysql connection when it's required and when MySQL timeout I don't need to restart the node.

Try this and see if there's any good:

dbConnectionInfo = {
  host: "",
  user: "",
  password: "",
  database: ""
};

var con = mysql.createPool(
  dbConnectionInfo
);

con.on('connection', function (connection) {
  console.log('DB Connection established');

  connection.on('error', function (err) {
    console.error(new Date(), 'MySQL error', err.code);
  });
  connection.on('close', function (err) {
    console.error(new Date(), 'MySQL close', err);
  });
});

This method I found from a post but I can't remember which one because there are a lot of mysl.createPool I've seen. You may find more methods here

Upvotes: 1

Related Questions