On 30 January 2016 at 08:22, Frank Millman <fr...@chagford.com> wrote: > There are times when I want to execute a SELECT statement, and test for > three possibilities - > - if no rows are returned, the object does not exist > - if one row is returned, the object does exist > - if more that one row is returned, raise an exception > > We had a recent discussion about the best way to do this, and ChrisA > suggested the following, which I liked - > > cur.execute('SELECT ...) > try: > row = next(cur) > except StopIteration: > # row does not exist > else: > try: > next_row = next(cur) > except StopIteration: > # row does exist > else: > # raise exception
The simplest thing would just be to call list(cur) but I realise that you don't want to consume more than 2 rows from the database so just use islice: rows = list(islice(cur, 2)) # pull at most 2 rows if not rows: # no rows elif len(rows) > 1: # too many rows row = rows[0] Depending on your application if you just want to raise any error when there's not exactly one row then you could just do: (row,) = list(islice(cur, 2)) -- Oscar -- https://mail.python.org/mailman/listinfo/python-list