Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a row exists in sqlite3?

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()
like image 391
Skamah One Avatar asked Mar 16 '23 04:03

Skamah One


1 Answers

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")
like image 178
CL. Avatar answered Mar 23 '23 14:03

CL.