RMRiver
RMRiver

Reputation: 645

How to verify if a mysql database is reachable quickly in python?

I have a mysql server running on my local network that isn't reachable off the network, and it needs to stay like this.

When I am on a different network the following code hangs for about 5-10 seconds, my guess is that its retrying to connect for a number of attempts:

import mysql.connector

conn = mysql.connector.connect(
            host="Address",
            user="user",
            password="password",
            database="database"
)

Is there a way to "ping" the mysql server before this code to verify that the MySQL server is reachable or limit the number of retries?

At the moment I am having to use a try-except clause to catch if the server is not reaachable.

Upvotes: 0

Views: 410

Answers (1)

MatsLindh
MatsLindh

Reputation: 52832

Instead of trying to implement specific behavior before connecting, adjust the connect timeout so that you don't have to wait - according to your need, the server is down if you can't connect within a short timeframe anyway.

You can use connection_timeout to adjust the socket timeout used when connecting to the server.

If you set it to a low value (seems like it's in seconds - so 1 should work fine) you'll get the behavior you're looking for (and it will also help you catch any issues with the user/password/database values).

Upvotes: 1

Related Questions