首页 > 解决方案 > 通过 psycopg2 确定异常类型

问题描述

我将 python 与 psycopg2 一起使用。以下代码段会产生某种错误,但我无法获得任何输出,因此我无法处理该错误

cur = conn.cursor()
try:
  cur.execute("INSERT INTO mqtt.records(client, id_type, value) VALUES (%(str)s, %(int)s, %(float)s)", (topic[1], switchCase(topic[-1]), msg.payload)
except psycopg2.Error as e:
  print(e)
conn.commit()
cur.close()

我很确定这是某种类型转换错误,但它没有被except psycopg2.Error as e:. 如果我使用一般except:来捕获任何异常,它会捕获。但后来我不知道如何获取错误消息

标签: pythonpython-3.xpsycopg2

解决方案


使用except Exception as e:我收到消息“参数不能混合”,这导致我认为这... VALUES (%(str)s, %(int)s, %(float)s)不起作用。

相反,我不得不对(str(topic[1]), int(switchCase(topic[-1])), float(msg.payload))部分进行类型转换。

所以我基本上误解了文档。我真丢脸。


推荐阅读