How to check if MySQL connection is alive?
-
I have an application that allows users to connect to a MySQL database by entering the hostname, schema, username, password, and other standard credentials. Once the user inputs this information and clicks the Connect button, the application attempts to establish a connection with the MySQL server. If successful, an icon updates to reflect the connected status, and the user is free to interact with the database. When finished, they can click the Disconnect button, which updates the icon to indicate the disconnected state.
The problem arises when unexpected events occur. These include things such as power outages, network disruptions, or similar issues. These can silently break the connection. In these cases,
QSqlDatabase::isOpen()
still returns true, even though the connection is no longer valid or stable.Given this situation, I’d like to know: what is the best approach for reliably checking whether the connection is still alive?
P.S. One idea I had was to create a separate thread that continuously checks the connection status (while the app is in a connected state) by periodically sending a lightweight query such as
SELECT 1
. If the query fails, the app would automatically switch to a disconnected state and stop the thread. However, I’m not sure if this is the recommended or standard way of handling such scenarios. -
Hi,
One possible thing you could try is grab the database handle and use the mysql_ping method.
Haven't done it myself so I can't guarantee