mysql icon indicating copy to clipboard operation
mysql copied to clipboard

Question: Is there a way to check if a connection is connected?

Open john1625b opened this issue 7 years ago • 2 comments

I am making a health check endpoint for kubernetes (google cloud's service to host containerized applications) for my mySql application.

right now I am using this package https://www.npmjs.com/package/health-check-mysql

But is there something built into the package itself, something like a isConnected method. ie: connection.isConnected() ? throw new Error('not connected to mysql') : null

john1625b avatar Apr 02 '18 16:04 john1625b

It's not documented (but if someone wants to write up some docs, that'd be awesome 👍), but each connection object has a state property. Connected would be connection.state === 'connected' || connection.state === 'authenticated'. But due to how the TCP sockets work in Node.js, this module is not notified if the TCP connection has been terminated (like if the MySQL server kills an idling connection) until a socket operation is attempted. This means that the only reliable way to know if the connection is good is to attempt an operation, like connection.ping.

dougwilson avatar Apr 02 '18 16:04 dougwilson

yes, you can put if condition when connection is connect print connected otherwise not connected. but make sure you assign connection code to a variable and thn put if condition on a vaariable...

your connection code here..

if($a){ echo connected; } else{ echo not connected; }

bhupirawat57 avatar Feb 20 '20 10:02 bhupirawat57