Python: How to check if an entry already exists in a sql database?
15,027
The statement
data = cur.fetchall()
will assign to data
an empty list, not None
, when nothing is found.
So just change your check to:
if not data:
instead of:
if data is None:
Author by
Admin
Updated on June 07, 2022Comments
-
Admin almost 2 years
I'm new to python and even newer to sql, but I have been trying to make this work all morning and I cannot seem to figure it out. I have a table setup called POSTS(id). I'm trying to check if a number is already in the id column, but it doesn't matter what number postid is because data never returns none even if postid is set to a number not in the database.
import sqlite3 as lite import sys con = lite.connect('post.db') postid = '52642' cur = con.cursor() cur.execute("select id from POSTS where id=?", (postid,)) data = cur.fetchall() if data is None: print ('not found') else: print ('found')
-
Freestyle076 over 9 yearsSimilarly you can use 'if data == []'
-
Alex Martelli over 9 years@Freestyle076, yes, but
if not data:
is faster -- and, not surprising, a more Pythonic idiom (Python's implementation tends to be optimized to make more idiomatic expressions faster).