pythonsqlalchemy

How to check and handle errors in SQLAlchemy


How do you handle errors in SQLAlchemy? I am relatively new to SQLAlchemy and do not know yet.

Before I used SQLAlchemy, I would do things like

status = db.query("INSERT INTO users ...")
if (!status):
    raise Error, db.error

But now I am coding in SQLAlchemy and I do things like

user = User('Boda Cydo')
session.add(user)
session.commit()

No error checking whatsoever!

I do not like this coding style without error checking at all.

Please advice on how to check and handle errors in SQLAlchemy!


Solution

  • Your example says:

    status = db.query("INSERT INTO users ...")
    if (!status):
        raise Error, db.error
    

    That seems to mean that you want to raise an exception if there's some error on the query (with raise Error, db.error). However sqlalchemy already does that for you - so

    user = User('Boda Cydo')
    session.add(user)
    session.commit()
    

    Is just the same. The check-and-raise part is already inside SQLAlchemy.

    Here is a list of the errors sqlalchemy itself can raise, taken from help(sqlalchemy.exc) and help(sqlalchemy.orm.exc):