Skip to Main Content

DevOps, CI/CD and Automation

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Proper handling of return results

_AZ_Aug 1 2017 — edited Aug 1 2017

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.

This post has been answered by Anthony Tuininga-Oracle on Aug 1 2017
Jump to Answer

Comments

_AZ_

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.

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!

Marked as Answer by _AZ_ · Sep 27 2020
_AZ_

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

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.

1 - 4
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Aug 29 2017
Added on Aug 1 2017
4 comments
1,427 views