Search code examples
pythonmysql-connectormysql-connector-python

mySQL Connector with Flask, how to check if the connection is open


I am a Flask app and I connect to a MySQL database with mysql connector python.

At the beginning of my app script I open the connection with

import mysql.connector
cnx = mysql.connector.connect(user=USER,
                              password=PASSWORD,
                              host=HOST,
                              database=DB,
                              # use_pure=False
                              )

Then I pass "cnx" in my functions and open and close the cursor within them.

I wonder how to check if the connection is still open, or has been closed for whatever reason so that I can open it again.

I saw this can be done with other modules I wonder how its done with mysql connector python.


Solution

  • I found the answer at https://stackoverflow.com/a/64220421/12040493

    the original question does not refer to this module hence it was tricky to find and I wanted to create a dedicated question for it.

    in short:

    You can check the connection with the is_connected method with this library python-mysql:

    cnx = connector.connect(user="user",password="pass",host="host",database="database")
    
    if (cnx.is_connected()):
        print("Connected")
    else:
        print("Not connected")
    

    Thank you Shadowtrooper