Python validation in SQLite3

I am trying to check if a variable exists in SQLite3 db. Unfortunately, I cannot get it to work. The airport table contains 3 columns, with ICAO being 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 works without errors, but the result is always the same (not found).

What is wrong with this code?

+6
source share
1 answer

Try this instead:

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

The return value of cursor.execute is the cursor (or, more precisely, the link to it) and does not depend on the results of the query. You can easily verify 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 

On the other hand, if you call cursor.fetchone result tuple or None, if there is no line that passes query conditions. Therefore, in your case, if c.fetchone(): will mean one of the following values:

 if (1, ): ... 

or

 if None: ... 
+7
source

Source: https://habr.com/ru/post/953881/


All Articles