0

In my Python script I use the "MariaDB Connector"-Modul and created a function called "db_exec" for executing SQL Statements. The funtion is working, but I try to fetch the errors and depending on the error I would like to do diffenrt things.


Function:

def db_exec(sql_statement):
...
sql_cmd = sql_statement.split()[0].lower()
try:
    cur.execute(sql_statement)
    if sql_cmd == "insert" or sql_cmd == "update":
        db_commit()
    try:
        result = cur.fetchall()
        return result
    except mariadb.Error as e:
        if e == "Cursor doesn't have a result set":
            print("do nothing")
            return False
        ...
        exit(1)
except mariadb.Error as e:
    if e == "Cursor doesn't have a result set":
        print("do nothing")
        return False
    ...
    exit(1)

Example: If I try:

name = "Tim"
db_exec(f"INSERT INTO my_table (name, created) VALUES ({name}, NOW()")

I only got "Process finished with exit code 1" and NOT "do nothing" with the return False of the "db_exec" function.

If I print the variable "e" I only get "Cursor doesn't have a result set" as the entrie Error-Message.

I didn't find a solution and unfortunately don't know under which keywords I need to look.

1 Answers1

0

I have now found a solution to my own question above, thanks to https://stackoverflow.com/users/541136/ from the post linked below.

def db_exec(sql_statement):
    sql_cmd = sql_statement.split()[0].lower()
    try:
        cur.execute(sql_statement)
        if sql_cmd == "insert" or sql_cmd == "update":
            db_commit()
        try:
            result = cur.fetchall()
            return result
        except mariadb.Error as e:
            for e_msg in e.args:
                if e_msg == "Cursor doesn't have a result set":
                    print("do nothing")
                    return False
            ...
            exit(1)
    except mariadb.Error as e:
        for e_msg in e.args:
            if e_msg == "Cursor doesn't have a result set":
                print("do nothing")
                return False
    ...
    exit(1)

Here the original more clearly answer: Manually raising (throwing) an exception in Python