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

13,878

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);
});
Share:
13,878
Demolition
Author by

Demolition

On Daytime : At Office, working. On Night : At home, Browsing. For Fun : Code, Code and Search for Code...

Updated on June 04, 2022

Comments

  • Demolition
    Demolition almost 2 years

    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