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 wa
Here is my final code for reference:
try:
df.to_sql(name='sql_table', con=engine, if_exists='append', index=False)
except exc.DBAPIError as ex:
if ex.orig.pgcode == '23502':
print("Data could not be uploaded to sql_table: " + ex.orig.diag.message_primary)
else:
raise
As you've pointed out in your question, you can access the underlying exception raised by the dbapi through the .orig
attribute of the SQLAlchemy exception.
Any exception that is raised by the driver and propagated through SQLAlchemy is wrapped by a subclass of DBAPIError, where it's docs state:
The wrapped exception object is available in the orig attribute. Its type and properties are DB-API implementation specific.
(emphasis mine)
Looking at the psycopg docs for their base Error one of the attributes they name is pgcode
:
String representing the error code returned by the backend, None if not available. The errorcodes module contains symbolic constants representing PostgreSQL error codes.
So, <sqla_exc>.orig.pgcode
looks like it should get what you are after, but if for whatever reason psycopg doesn't make their code available in their exception state, its not really something that sqlalchemy can address as it just wraps their exception and passes it on to you.