4

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()
Skamah One
  • 2,456
  • 6
  • 21
  • 31

4 Answers4

4

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")
CL.
  • 173,858
  • 17
  • 217
  • 259
2

Something like this?

vals = cursor.execute("SELECT name, age FROM people WHERE pin=?", (pin, )).fetchone()

if vals:
    name, age = vals
ODiogoSilva
  • 2,394
  • 1
  • 19
  • 20
2

Alternatively you may use EXISTS to validate the query if your table is large and you will benefit with index on pin, take a look at this SO, so you may do:

c = cursor.execute("""SELECT EXISTS (SELECT 1 
                                     FROM people 
                                     WHERE pin=?
                                     LIMIT 1)""", (pin, )).fetchone()[0]
if c:
    ...

The cursor will return either (1,) (if 1 or more rows returned) or (0,) (if None returned), c will be either 1/0 as fetchone()[0] will get the integer value 1/0 from above.

Exists could be more efficient depending on the size of your table and if you have index set on the field you query.

Community
  • 1
  • 1
Anzel
  • 19,825
  • 5
  • 51
  • 52
1

You could use a count query:

if c.execute("SELECT count(*) FROM people WHERE pin=?", (pin, )).fetchone()[0] > 0:
    ...
Reto Aebersold
  • 16,306
  • 5
  • 55
  • 74