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?
First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.
The sqlite3. connect() function by default will open databases in rwc , that is Read, Write & Create mode, so connecting to a non-existing database will cause it to be created. See the SQLite URI Recognized Query Parameters documentation for more details on what parameters are accepted.
Show activity on this post. import MySQLdb db = MySQLdb. connect(passwd="moonpie", db="thangs") results = db. query("""SELECT * from mytable limit 1""") if not results: print "This table is empty!"
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:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With