且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python检查SQLite3中是否存在

更新时间:2023-01-19 14:23:52

尝试以下方法:

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