18

I have some code where I try to write to a database, and in some cases get an (expected) integrityerror due to a uniqueness constraint. I am trying to catch the error, but for some mysterious reason I cannot. My code looks like this (running in a loop, simplified for clarity):

from psycopg2 import IntegrityError
try:
    data = {
            'one': val1,
            'two': val2
        }

    query=tablename.insert().values(data)
    target_engine.execute(query)
except IntegrityError as e:
    print "caught"
except Exception as e:
    print "uncaught"
    print e
    break

The output when I run the script looks like this:

uncaught
(psycopg2.IntegrityError) duplicate key value violates unique constraint "companies_x_classifications_pkey"
DETAIL:  Key (company_id, classification_id)=(37802, 304) already exists.
 [SQL: 'INSERT INTO companies_x_classifications (company_id, classification_id) VALUES (%(company_id)s, %(classification_id)s)'] [parameters: {'classification_id': 304, 'company_id': 37802L}]

It never even prints "caught", so it doesnt think I have an integrityerror. Yet when I print the error, it is an integrity error. Any help will be appreciated!

Leo
  • 288
  • 1
  • 2
  • 9

1 Answers1

22

Since you are using sqlalchemy, try:

from sqlalchemy.exc import IntegrityError

try:
...
except IntegrityError as e:
    print "caught"

The sqlalchemy wraps the psycopg2 exception to its own exception

piro
  • 13,378
  • 5
  • 34
  • 38
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57