Logan
Logan

Reputation: 21

Python: How to check if an entry already exists in a sql database?

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')

Upvotes: 2

Views: 19876

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881575

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:

Upvotes: 7

Related Questions