Reputation: 243
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
Upvotes: 2
Views: 7265
Reputation: 2885
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.
Upvotes: 3