Bert Maier
Bert Maier

Reputation: 71

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

Upvotes: 2

Views: 4341

Answers (2)

tfv
tfv

Reputation: 6259

You can use the ON CONFLICT clause clause. This will be part of the SQL statemant and give you a chance to cover for errors in a CREATE etc statement.

For INSERT, the actual syntax reads INSERT OR IGNORE instead of INSERT, other options like abort or rollback can also be found in that link.

[EDIT]

I have also attached an example with error which shows the feasibility of alecxe's answer below. His answer seems to be the better approach:

import sqlite3 as lite

con = lite.connect('test.db')

with con:
    cur = con.cursor()    
    cur.execute("CREATE TABLE Persons(Id INT, Name TEXT)")
    cur.execute("INSERT INTO Persons VALUES(1,'Joe')")
    cur.execute("INSERT INTO Persons VALUES(1,'Jenny')")

    try:
        cur.execute("INSERT INTO Persons VALUES(1,'Jenny', 'Error')")
        self.con.commit()

    except lite.Error as er:
        print 'er:', er.message

#Retrieve data
    cur.execute("SELECT * FROM Persons")
    rows = cur.fetchall()
    for row in rows:
        print row    

Upvotes: 2

alecxe
alecxe

Reputation: 473763

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)

Upvotes: 5

Related Questions