首页 > 解决方案 > 如何在 python 中捕获 pg8000.core.IntegrityError 异常?

问题描述

当尝试使用pg8000加载到 postgresql 中的表时,我正在尝试运行测试用例以捕获主键异常。但是,我无法在 python 中捕捉到它。下面是我的代码。

import pg8000

def create_albums(self,music):
    experts = []
    exp = music.data_info.get("artist_list")  # List of a dictionary
    try:
        for expert in exp:
            experts.append(ArtistData({
                "name": expert.name,
                "age": expert.age,
                "present": True,
                "nodiscs": expert.get("disc_code")
                }))
    except pg8000.core.IntegrityError:
        raise Exception
    return experts

下面是错误信息

pg8000.core.IntegrityError: {'S': 'ERROR', 'V': 'ERROR', 'C': '23505', 'M': 'duplicate key value violates unique constraint "artist_discs_pkey"}

非常感谢任何帮助。谢谢你。

标签: pythonpostgresqlpg8000

解决方案


您确实捕获了异常,但您所做的只是再次引发它,因此它毫无用处。

在加注之前添加一个简单的打印,例如。print("Failed to insert"),您将看到该消息后跟引发该消息的异常。


推荐阅读