简体   繁体   中英

How can I get an error when no results are fetched with DB query?

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:

  1. How can I and How should I query for .all() or .one() , and deal with the issue of not having any rows returned?
  2. How can I and how should I deal with others SQL or System related errors? I would like to record them and observe them to fix issues.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM