Written by Sean Behan on Thu May 10th 2018

If you're working with SQLAlchemy, the best database driver for Python, and want to see only SQL syntax errors, you need to use the StatementError exception class. On it, is an attribute orig, that contains just the SQL syntax error... and not any database driver info or even the full stack trace.

Below is what the standard ProgrammingError exception class will return as it's error message. It's got everything in it, but if you want to look at just the SQL syntax error, it's too much.

(psycopg2.ProgrammingError) relation "userds" does not exist
LINE 1: select * from userds
 [SQL: 'select * from userds'] (Background on this error at: http://sqlalche.me/e/f405)

But here is the code to get at just the important part

from sqlalchemy.exc import StatementError

 [r for r in db.execute("an invalid sql statement")]
except StatementError as error:

Which will output

relation "userds" does not exist

You can read the source code for it here https://github.com/zzzeek/sqlalchemy/blob/699272e4dcb9aa71ebbc0d9487fb6de82d3abc2b/lib/sqlalchemy/exc.py#L280

Tagged with..
#python #sql #sqlalchemy #programming #databases #exceptions #debugging

Just finishing up brewing up some fresh ground comments...