8

I'm trying to check whether a variable exists in an SQLite3 db. Unfortunately I can not seem to get it to work. The airports table contains 3 colums, with ICAO as the first column.

if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')") is True:
    print("Found!")
else:
    print("Not found...")

The code runs without any errors, but the result is always the same (not found).

What is wrong with this code?

3 Answers 3

9

Try this instead:

c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")

if c.fetchone():
    print("Found!")

else:
    print("Not found...")

Return value of cursor.execute is cursor (or to be more precise reference to itself) and is independent of query results. You can easily check that:

 >>> r = c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")
 >>> r is True
 False
 >>> r is False
 False
 >>> r is None
 False

 >>> r is c
 True

From the other hand if you call cursor.fetchone result tuple or None if there is no row that passes query conditions. So in your case if c.fetchone(): would mean one of the below:

if (1, ):
    ...

or

if None:
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work for me, as EXISTS either returns a 0 or 1 in sqlite3. See the docs (sqlite.org/lang_expr.html): "The EXISTS operator always evaluates to one of the integer values 0 and 1. If executing the SELECT statement specified as the right-hand operand of the EXISTS operator would return one or more rows, then the EXISTS operator evaluates to 1. If executing the SELECT would return no rows at all, then the EXISTS operator evaluates to 0. " So you can change the answer from None to (0,). I will edit if nobody objects in the next few days.
1

Let's prepare a database to test it.

import sqlite3
c = sqlite3.connect(":memory:")
c.execute("CREATE TABLE airports (ICAO STRING, col2 STRING, col3 STRING)")
c.execute("INSERT INTO airports (ICAO, col2, col3) VALUES (?, ?, ?)", ('EHAM', 'value2', 'value3'))

Since your SELECT 1 FROM airports WHERE ICAO = 'EHAM' already serves the purpose of checking existence, let's use it directly, without the redundant SELECT EXISTS()

if c.execute("SELECT 1 FROM airports WHERE ICAO = 'EHAM'").fetchone():
    print("Found!")
else:
    print("Not found...")

the result is

Found!

Let's check a non-existent case

if c.execute("SELECT 1 FROM airports WHERE ICAO = 'NO-SUCH'").fetchone():
    print("Found!")
else:
    print("Not found...")

the result is

Not found...

If you just want to fix your code, you can try

if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO = 'EHAM')").fetchone() == (1,):
    print("Found!")
else:
    print("Not found...")

the result is

Found!

Comments

1

Thanks for the answer from zero323, although the code snippet is wrong, as fetchone() does not return True or False. It only returns 1 for True and 0 for False. (binary) The following code works without problems in Python3:

response = self.connection.execute("SELECT EXISTS(SELECT 1 FROM invoices WHERE id=?)", (self.id, ))
fetched = response.fetchone()[0]
if fetched == 1:
    print("Exist")
else:
    print("Does not exist")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.