Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 567
Phil Avatar asked Oct 18 '25 11:10

Phil


1 Answers

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')
like image 118
Jasper van den Bosch Avatar answered Oct 20 '25 01:10

Jasper van den Bosch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!