【问题标题】:How to catch pg8000.core.IntegrityError exception in python?如何在 python 中捕获 pg8000.core.IntegrityError 异常?
【发布时间】:2020-03-08 17:53:38
【问题描述】:

当我尝试使用 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"}

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

【问题讨论】:

  • 运行代码时究竟发生了什么?
  • 所以(主键)PK 是名称和 disc_code。当我有相同的名字和相同的 disc_code。它发出“重复键值违反唯一约束”。

标签: python postgresql pg8000


【解决方案1】:

你确实捕获了异常,但你所做的只是再次引发它,所以它相当没用。

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

【讨论】:

    【解决方案2】:

    根据documentation

    "pg8000.core.IntegrityError:" 属于泛型(DatabaseError)。所以你需要像这样格式化你的代码,用 DatabaseError 替换 IntegrityError:

    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.DatabaseError:
            raise Exception
        return experts
    

    【讨论】:

      猜你喜欢
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      相关资源
      最近更新 更多