Bert Maier Bert Maier - 2 years ago 57
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


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 Source

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

    cursor.execute("INSERT INTO ...", params)
except sqlite3.Error as err:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download