How to reconnect using Pool in nodejs' promise-mysql if the connection went down?

887 views Asked by At

I am employing promise-mysql NodeJs library to make awaitable operations against a MySQL server.

Presently I have a simple config:

 let pool = await mysql.createPool(dbConfig);
 let connection = await pool.getConnection();

 /// after the connection is made on the program start, once,
 /// some querying using the connection follows

However, just one connection seems to get disconnected. Question: how to implement the automatic handling of a disconnect and bringing up a subsequent new connection if current one was dropped?

1

There are 1 answers

0
Vikas Keskar On

This is working solution for me

pool.getConnection((err, connection) => {
  if (err) {
    console.log('Error while connecting ', err)
  } else {
    if (connection) connection.release()
    console.log('Database Connected Successfully!')
  }
})

Replace this let connection = await pool.getConnection(); with above code. And execute your queries with pool and not with the connection. So, if your single connection went down or is busy, then your query will be executed with another connection from pool.