2

I can't seem to find a simple answer for this question. I am using MySQLdb for Python and I am running a select statement, I want to check if an empty query set is returned.

get_port = db.cursor()
get_port.execute(""" SELECT port FROM nar_ports WHERE port=%s AND hostname=%s;""", (device_port,PE))

I have tried

if not get_port:

This doesn't match. So then I tried

for result in get_port.fetchall():
    existing_port = result[0]
if not existing_port:

But it doesn't even seem to enter the loop. So then I tried to check the length

if len(get_port) == 0:

But it seems you can't run len on a sql object. So I check if the object has a none value.

if get_port = None:

But this doesn't seem to work either.

I'm certain there is a simple solution for this but I cannot seem to find it. Any help would be greatly appreciated. Thanks in advance.

cheers

1 Answer 1

3

It is simple, though you almost had a longer way.

if get_port.fetchone():
    do_something_here()

You could also have used

if len(get_port.fetchmany()):
    do_something_here()

But that is longer and less efficient.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey Pydsigner, man I was so close, dam! lol. Thank you for your response, that worked. Thanks so much!
No problem! It's a pleasure to help people who have already done so much to help themselves. BTW, you can accept and/or upvote my answer, which will help other helpful people from coming in to answer your question again.
Thank you and the same to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.