pythonmysqlmysql-connector-python

How to Handel exception during Mysql connection


I m trying to connect to a mysql database. if server is not responding, my application crashes. I am using try, except but looks like two exceptions are raising and "try: except" could not handle it. can some one figure it out where is the problem. below is my code:-

def check_server(server_address):

    con = mysql.connector.connect(host='{}'.format(server_address),
                                  database='domicile_reports',
                                  user='xyz',
                                  password='xyz')

    try:

        if con.is_connected():
            print('{} Connected'.format(server_address))
            con.close()
    except Exception as e:
        print("Can not connect to db. {} Occured".format(e)) 
 check_server('25.13.253.67')

Error displayed on terminal:- Traceback (most recent call last): File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector
network.py", line 574, in open_connection self.sock.connect(sockaddr) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "f:\Docs\OneDrive\Python Projects\CFC App\splash_screen_gui.py", line 151, in obj = splashscreen() File "f:\Docs\OneDrive\Python Projects\CFC App\splash_screen_gui.py", line 51, in init self.check_server(self.server_2) File "f:\Docs\OneDrive\Python Projects\CFC App\splash_screen_gui.py", line 80, in check_server con = mysql.connector.connect(host='{}'.format(server_address), File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector_init_.py", line 273, in connect return MySQLConnection(*args, **kwargs) File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\connection.py", line 116, in init self.connect(**kwargs) File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\abstracts.py", line 1052, in connect self._open_connection() File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\connection.py", line 494, in _open_connection
self._socket.open_connection() File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\network.py", line 576, in open_connection
raise errors.InterfaceError( mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '25.13.253.67:3306' (10060 A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)


Solution

  • You need to put the connect() call inside the try: except block. You can also use a context manager to properly close the connection, example:

    import mysql.connector
    
    from mysql.connector.errors import Error
    
    
    def check_server(server_address):
        try:
            with mysql.connector.connect(
                host=server_address,
                database="domicile_reports",
                user="xyz",
                password="xyz",
            ) as cnx:
                print(f"{server_address} Connected")
        except Error as err:
            print(f"Can not connect to db. {err} Occured")
    
    
    check_server("25.13.253.67")