Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if exists in SQLite3

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?

like image 419
Caesius Avatar asked Sep 15 '13 21:09

Caesius


People also ask

How do I check SQLite data in Python?

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.

How do I check if a SQL database exists in Python?

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.

How do I check if a Python database is empty?

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!"


1 Answers

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:
    ...
like image 146
zero323 Avatar answered Oct 30 '22 20:10

zero323