为什么psycopg2 IntegrityError没有被捕获?

时间:2015-08-06 08:33:25

标签: python error-handling sqlalchemy psycopg2

我有一些代码,我尝试写入数据库,并且在某些情况下由于唯一性约束而获得(预期的)完整性错误。我试图抓住错误,但由于一些神秘的原因,我不能。我的代码看起来像这样(在循环中运行,为了清晰起见而简化):

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

运行脚本时的输出如下所示:

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}]

它甚至从未打印过#34;因此它并不认为我有完整的错误。然而,当我打印错误时,这是​​一个完整性错误。 任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:17)

由于您使用的是sqlalchemy,请尝试:

from sqlalchemy.exc import IntegrityError

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

sqlalchemypsycopg2例外包装到自己的例外