Python check if exists in SQLite3

天涯浪子 提交于 2020-01-02 03:13:22

问题


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


来源:https://stackoverflow.com/questions/18817699/python-check-if-exists-in-sqlite3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!