【问题标题】:Why is psycopg2 IntegrityError not being caught?为什么 psycopg2 IntegrityError 没有被捕获?
【发布时间】: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


    【解决方案1】:

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

    from sqlalchemy.exc import IntegrityError
    
    try:
    ...
    except IntegrityError as e:
        print "caught"
    

    sqlalchemypsycopg2 异常包装到它自己的异常中

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 2010-11-16
      • 2010-12-25
      • 2012-01-22
      相关资源
      最近更新 更多