Python check if exists in SQLite3

2019-04-28 04:17发布

问题:

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?

回答1:

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:
    ...