How to access psycopg2 error wrapped in sqlalchemy error

前端 未结 2 805
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 14:21

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

相关标签:
2条回答
  • 2020-12-21 15:02

    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
    
    0 讨论(0)
  • 2020-12-21 15:23

    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.

    0 讨论(0)
提交回复
热议问题