Python检查SQLite3中是否存在 [英] Python check if exists in SQLite3
问题描述
我正在尝试检查SQLite3数据库中是否存在变量.不幸的是,我似乎无法使其正常工作.机场表包含3个列,国际民航组织为第一列.
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).
此代码有什么问题?
推荐答案
尝试以下方法:
c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")
if c.fetchone():
print("Found!")
else:
print("Not found...")
cursor.execute
的返回值是游标(或更精确地引用其自身),并且独立于查询结果.您可以轻松地检查以下内容:
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
另一方面,如果您调用cursor.fetchone
结果元组,或者如果没有行通过查询条件,则为None.因此,在您的情况下,if c.fetchone():
表示以下之一:
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, ):
...
或
if None:
...
这篇关于Python检查SQLite3中是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!