now available
Want fresh tech tips in your inbox?

How to Just Get SQL Statement Error with SQLAlchemy Python Database Wrapper


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 w/ #python #sql #sqlalchemy #programming #databases #exceptions #debugging

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app