小编Leo*_*Leo的帖子

为什么psycopg2 IntegrityError没有被捕获?

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

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
Run Code Online (Sandbox Code Playgroud)

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

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}]
Run Code Online (Sandbox Code Playgroud)

它甚至从未打印过"抓住",所以它并不认为我有完整的错误.然而,当我打印错误时,这是​​一个完整性错误.任何帮助将不胜感激!

python error-handling sqlalchemy psycopg2

15
推荐指数
1
解决办法
6161
查看次数

标签 统计

error-handling ×1

psycopg2 ×1

python ×1

sqlalchemy ×1