1

I have this sql query in python using psycopg:

cr.execute('select id from test_table where va1_1=%s
            order by val_2 desc limit 1',(id, ))

if the query has multiple records, this way im only fetching the last one. i then assign the result to a variable:

x=cr.fetchone()[0]

however, sometimes the query does not return any records, and assigning it with cr.fetchone will naturally result in an error. what's the proper way to first check if the query would return records before trying to assign it?
i tried a simple:

if cr.exec....:
    x=cr.fetchone()[0]

but it seems that it's always returning False and always not performing fetchone.

1 Answer 1

3

you could check if the result is none first. fetchone returns None when there are no more results.

x = cr.fetchone()
if x is not None:
  result = x[0]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks dm, i guess i shouldve read more about fetchone first!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.