I'm trying to learn and advance with SQLAlchemy. Today I wanted to learn about exceptions it raises.
I'm working on a Pyramid based project, MySQL server (InnoDB) and SQLAlchemy.
I am trying to except all errors since NoResultFound
error would not raise or print in console. So I except exc.SQLAlchemyError
.
When I query my table and no results are found, it does not raise or catch or except anything whatsoever and continues operating.
Questions:
.all()
or .one()
, and deal with the issue of not having any rows returned? My code is:
try:
query = Session.query(MyTable).filter(Terms.column == my_string).all()
except exc.SQLAlchemyError, e:
print e
return False
(Instead of exc.SQLAlchemyError, I first tried NoResultFound, e)
Indeed this code will not raise an exception if no records are found. So instead you should throw your own exception:
import logging
try:
records = Session.query(MyTable).\
filter(Terms.column == my_string).all()
if len(records) == 0:
raise MyException('No records found')
except MyException, e:
logging.info('No records found')
except exc.SQLAlchemyError, e:
logging.exception('Some problem occurred')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.