我正在使用 SQLalchemy 和 psycopg2 将 Pandas 数据框上传到 Postgres 中的表。如何访问 SQLalchemy 错误中的 psycopg2 错误?
我想仅在由于违反非空约束的列中的空值而引发错误时才将异常写入我的代码。我知道如何使用 psycopg2 测试这个确切的 pSQL 错误,但是当我运行我的代码时,它返回一个 SQLalchemy 错误。
这是错误:
SQLalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) 列中的空值...
这是必要的例外:
from sqlalchemy import exc
try:
df.to_sql(name='sql_table', con=engine, if_exists='append', index=False)
except exc.IntegrityError:
Run Code Online (Sandbox Code Playgroud)
这是我想要做的:
from sqlalchemy import exc
import psycopg2
try:
df.to_sql(name='sql_table', con=engine, if_exists='append', index=False)
except exc.IntegrityError as ex:
ex = ex.psycopg2error
if ex.pgcode == '23502'
print('Data not uploaded: null value in a column violates non-null constraint')
else:
raise
Run Code Online (Sandbox Code Playgroud)
我知道我可以 test sqlalchemy.exc.IntegrityEror.orig,但这不像使用pgcode成员那样干净或细粒度。