mysql
mysql copied to clipboard
Question: Is there a way to check if a connection is connected?
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
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.
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; }