【发布时间】:2015-10-29 07:17:09
【问题描述】:
我有一些代码尝试写入数据库,但在某些情况下,由于唯一性约束,会出现(预期的)完整性错误。我试图捕捉错误,但由于某种神秘的原因,我不能。我的代码看起来像这样(循环运行,为清楚起见进行了简化):
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}]
它甚至从不打印“caught”,所以它不认为我有完整性错误。然而,当我打印错误时,这是一个完整性错误。 任何帮助将不胜感激!
【问题讨论】:
标签: python error-handling sqlalchemy psycopg2