How do I properly check if a row exists in my database table using Python 3 and sqlite3?
Here's my original code:
cursor.execute("SELECT name, age FROM people WHERE pin=?", (pin, ))
name, age = cursor.fetchone() or ('', 0)
So currently I'm setting them a default value with the or ('', 0)
, and I really don't like this.
Is there a way to check if the person already exists? Something like this (pseudo):
if cursor.exists("pin IN people"):
cursor.execute("SELECT name, age FROM people WHERE pin=?", (pin, ))
name, age = cursor.fetchone()
Don't call fetchone()
; just treat the cursor as an iterator:
for row in c.execute("SELECT name, age FROM ..."):
name, age = row
break
else:
print("not found")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With