我有一些代码试图写入数据库,在某些情况下,由于唯一性约束而得到(预期的)完整性错误。我正在试图找出错误,但由于一些神秘的原因,我不能。我的代码如下所示(在循环中运行,为了清晰起见,简化了):
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}]
它甚至从来没有打印“捕捉”,所以它不认为我有一个完整性错误。然而,当我打印错误时,这是一个完整性错误。任何帮助都将不胜感激!
发布于 2015-08-06 08:39:32
由于您正在使用sqlalchemy,请尝试:
from sqlalchemy.exc import IntegrityError
try:
...
except IntegrityError as e:
print "caught"
sqlalchemy
将psycopg2
异常包装为自己的异常。
https://stackoverflow.com/questions/31850710
复制相似问题