Forum Stats

  • 3,770,444 Users
  • 2,253,115 Discussions
  • 7,875,457 Comments

Discussions

Proper handling of return results

_AZ_
_AZ_ Member Posts: 494
edited Aug 1, 2017 2:23PM in Python

Hello,

what is the proper approach to handling 0 rows select results in the function like below:

def getValues(self, ts = datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S')):

  cursor = self.con.cursor()  cursor.execute("select ts_mi, stddev  from v_bigview where ts_mi = to_Date(:times,'YYYY/MM/DD HH24:MI:SS') " , times=ts)  tim, val = cursor.fetchone()  cursor.close()  print(current_fn_name(), "Fetched for {} values - {}".format(ts, tim, val))  return (tim, val)

thank you.

_AZ_

Best Answer

  • Anthony Tuininga-Oracle
    Anthony Tuininga-Oracle Member Posts: 37 Employee
    edited Aug 1, 2017 2:04PM Accepted Answer

    Well, with the code you have above you *will* get an error: TypeError: 'NoneType' object is not iterable. The reason for that is that fetchone() returns None if there are no rows left to fetch. That error isn't too helpful, though. You will need to do something along these lines:

    row = cursor.fetchone()

    if row is None:

       raise Exception("Hey, only one row was returned!")

    tim, val = row

    You will want to replace the Exception message with something a bit more meaningful, of course!

Answers

  • _AZ_
    _AZ_ Member Posts: 494
    edited Aug 1, 2017 1:41PM

    i think i should elaborate that I do expect to receive only one row ( from the select). Anything more (or less) should be deemed an error.

  • Anthony Tuininga-Oracle
    Anthony Tuininga-Oracle Member Posts: 37 Employee
    edited Aug 1, 2017 2:04PM Accepted Answer

    Well, with the code you have above you *will* get an error: TypeError: 'NoneType' object is not iterable. The reason for that is that fetchone() returns None if there are no rows left to fetch. That error isn't too helpful, though. You will need to do something along these lines:

    row = cursor.fetchone()

    if row is None:

       raise Exception("Hey, only one row was returned!")

    tim, val = row

    You will want to replace the Exception message with something a bit more meaningful, of course!

  • _AZ_
    _AZ_ Member Posts: 494
    edited Aug 1, 2017 2:12PM

    thank you @Anthony . Is there a better approach that i should.could use ( vs fetchone or overall ) ?

  • Anthony Tuininga-Oracle
    Anthony Tuininga-Oracle Member Posts: 37 Employee
    edited Aug 1, 2017 2:19PM

    You're welcome. That approach works and is reasoanble. If you want to check for too many rows as well, you can do fetchall() which will return an array and check the length of the array instead. If you're worried about getting back too many rows with fetchall() you can also use fetchmany(2) which will tell you if there are 0, 1, or 2 rows available.

    _AZ_
This discussion has been closed.