Skretch
Skretch

Reputation: 69

Python if statement skipping code even though condition is met

I am trying to check if an entry is already in the database and add the entry if it isn't but the if statement never runs even though the condition is met.

        userCurs.execute("SELECT EXISTS(SELECT 1 FROM images WHERE imageLink=?)", (image,))
        exists = userCurs.fetchone()
        if exists is None:
            addImage(userName,image,'','')
        else:
            print '--------> image skipped'
            print userCurs.fetchone()

I get this output:

--------> image skipped
None
--------> image skipped
None

and no entries are made to the database

Upvotes: 1

Views: 1166

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1125058

Don't call cursor.fetchone() again; the next row is always empty. Reuse the variable. You are fetching a (0,) or (1,) tuple; you could use tuple assignment to extract the flag value (note the comma on exits, =):

exists, = userCurs.fetchone()
if not exists:
    addImage(userName, image, '', '')
else:
    print '--------> image skipped'
    print exists

Now exists will be set to 0 or 1, rather than (0,) or (1,) and the if not exists: test will not pass for the 0 case.

Upvotes: 0

Michael Burr
Michael Burr

Reputation: 340506

The SQL statement:

SELECT EXISTS(SELECT 1 FROM images WHERE imageLink=?)

will always return a single row. The value of the column in that row will be the result of the EXISTS() function, which will be TRUE if any matches are found, or FALSE otherwise.

Since your original code only tested for the existence of a row in the result, and the full statement will always return exactly one row, you get the behavior you see.

What I think you should do is have your query return a rowset that has zero rows if no matches are found, and one (or more) rows if matches are found:

userCurs.execute("SELECT 1 FROM images WHERE imageLink=?", (image,))

Now your original test should work - if no imageLinks match the query, then there will be no rows in the result, so the first fetchone() will return a null object as you expect.

Of course, as several others have mentioned, you should ony call fetchone() once per row since it moves the cursor.

Upvotes: 3

Skretch
Skretch

Reputation: 69

Solved it by changing the code to

        userCurs.execute("SELECT EXISTS(SELECT 1 FROM images WHERE imageLink=?)", (image,))
        exists = userCurs.fetchone()
        if exists[0] == 0:
            addImage(userName,image,'','')
        else:
            print '--------> image skipped'
            print exists

As people have said the calling fetchone() twice gives different results the actual value of exists was (0,)

Upvotes: 1

Related Questions