I'm uploading a pandas data frame to a table in Postgres using SQLalchemy and psycopg2. How do I access the psycopg2 error that is within the SQLalchemy error?
I want to write an exception into my code only when it raises an error because of a null value in a column that violates not-null constraint. I know how to test for this exact pSQL error with psycopg2, but when I run my code it returns a SQLalchemy error.
Here's the error:
SQLalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column...
Here's the necessary exception:
from sqlalchemy import exc
try:
df.to_sql(name='sql_table', con=engine, if_exists='append', index=False)
except exc.IntegrityError:
Here's what I want to do:
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
I know I can test sqlalchemy.exc.IntegrityEror.orig
, but that is not as clean or fine-grained as using the pgcode
member.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…