How to check if the db connection is success or not in node js and mysql

Viewed 14990

I'm using mysql connection pool to create connection. The code looks like the following.

var pool = mysql.createPool(connectionProps);

by accessing pool, I'll get the an Object, even if the connection is not Successful. I checked it with starting and stopping mysql.

What I want is that, I need to check connection is successful or not as follows.

if(pool){ // mysql is started && connected successfully.
   console.log('Connection Success');
   doSomething();
}else{
   console.log('Cant connect to db, Check ur db connection');
}

I want something like this. So how can we do this with the mysql pool Object. Can someone please help me?

Thanks n Regards

2 Answers

Commonly you would do something like select something arbitrary from the db, and catch an error if that failed. Example from the docs.

const pool = mysql.createPool(connectionProps);
pool.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});
var pool = mysql.createPool(config.db);
exports.connection = {
query: function () {
    var queryArgs = Array.prototype.slice.call(arguments),
        events = [],
        eventNameIndex = {};

    pool.getConnection(function (err, conn) {
        if (err) {
            if (eventNameIndex.error) {
                eventNameIndex.error();
            }
        }
        if (conn) { 
            var q = conn.query.apply(conn, queryArgs);
            q.on('end', function () {
                conn.release();
            });

            events.forEach(function (args) {
                q.on.apply(q, args);
            });
        }
    });

    return {
        on: function (eventName, callback) {
            events.push(Array.prototype.slice.call(arguments));
            eventNameIndex[eventName] = callback;
            return this;
        }
    };
}
};

And require to use it like:

db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
      .on('result', function (row) {
        setData(row);
      })
      .on('error', function (err) {
        callback({error: true, err: err});
      });
Related