Bert Maier Bert Maier - 7 months ago 10
Python Question

How to handled SQLITE errors such as "has no column named" that are not raised as Exceptions?

what is the best way to catch the "errors" from the SQLite DB in Python as they are not considered as exceptions in Python.

The error output after I tried an INSERT OR IGNORE statement where a column did not exist in the DB is as follows

('table X has no column named Y,)


The following statement is used to execute the query

cursor.execute("INSERT...")


THe approach I thought of, does not work as a rowcount is not returned when there is an error on the cursor/ query

if cursor.rowcount != 1:
print("##########Error write_DB\n")


Is there something else I could do to catch similar erros.

Background: I am inserting multiple rows and I wanted to highlight in a logfile if the insert query was not sucessfull.

Thanks for you advice

Answer

You can follow the EAFP approach, use regular INSERT (without the "ignore" part) and catch database errors which you can log:

try:
    cursor.execute("INSERT INTO ...", params)
except sqlite3.Error as err:
    logger.error(err.message)
Comments