'mysql-connector-python: Know if data was requested from the database

I have a simple function that I have used many times in various projects, its purpose is to query in mysql. In the case of a request for data (SELECT) to return the data, and in the case of sending data (INSERT / UPDATE) to return the lastrowid:

def database (template, *data, **kdata):
    connector = mysql.connector.connect(
        host="XXX.XXX.XXX.XXX",
        user="root",
        password="XXXXXXXXXXXXXXX",
        database="XXXXX"
    )
    c=connector.cursor()
    if kdata: data=kdata
    c.execute(template,data)
    try:
        r = c.fetchall()
    except:
        r = c.lastrowid
    connector.commit()
    connector.close()
    return r

I recently uploaded a project to the cloud and gritted my teeth a lot to understand why the same code that works great on my PC stops working in the cloud. After a few tries I realized that this was a backward compatibility issue: my computer had version 8.0.21 installed in which an INSERT / UPDATE query attempted to call c.fetchall() would result in an error, which was for me the indication that no data was requested from the db. The latest version (8.0.28) was installed during the building of the container, in which case, a call to c.fetchall() will return empty data ([]). As a temporary solution I made sure to install version 8.0.21 on the container, but I do not want to block the project of future development. I would like to know if in the same structure of a function (without changing the dozens of times I call it) there is a way to get an indication whether data was requested from DB or just data was sent to it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source