簡體   English   中英

Python 檢查 SQLite3 中是否存在

[英]Python check if exists in SQLite3

我正在嘗試檢查 SQLite3 數據庫中是否存在變量。 不幸的是,我似乎無法讓它工作。 機場表包含 3 列,ICAO 作為第一列。

if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')") is True:
    print("Found!")
else:
    print("Not found...")

代碼運行沒有任何錯誤,但結果始終相同(未找到)。

這段代碼有什么問題?

試試這個:

c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")

if c.fetchone():
    print("Found!")

else:
    print("Not found...")

cursor.execute返回值是游標(或者更准確地說是對自身的引用)並且與查詢結果無關。 您可以輕松檢查:

 >>> 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():意味着以下之一:

if (1, ):
    ...

要么

if None:
    ...

讓我們准備一個數據庫來測試它。

import sqlite3
c = sqlite3.connect(":memory:")
c.execute("CREATE TABLE airports (ICAO STRING, col2 STRING, col3 STRING)")
c.execute("INSERT INTO airports (ICAO, col2, col3) VALUES (?, ?, ?)", ('EHAM', 'value2', 'value3'))

由於您的SELECT 1 FROM airports WHERE ICAO = 'EHAM'已經用於檢查存在的目的,讓我們直接使用它,沒有多余的SELECT EXISTS()

if c.execute("SELECT 1 FROM airports WHERE ICAO = 'EHAM'").fetchone():
    print("Found!")
else:
    print("Not found...")

結果是

Found!

讓我們檢查一個不存在的案例

if c.execute("SELECT 1 FROM airports WHERE ICAO = 'NO-SUCH'").fetchone():
    print("Found!")
else:
    print("Not found...")

結果是

Not found...

如果你只是想修復你的代碼,你可以試試

if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO = 'EHAM')").fetchone() == (1,):
    print("Found!")
else:
    print("Not found...")

結果是

Found!

感謝 zero323 的回答,盡管代碼片段是錯誤的,因為fetchone()不返回 True 或 False。 它只為 True 返回 1,為 False 返回 0。 (二進制)以下代碼在 Python3 中沒有問題:

response = self.connection.execute("SELECT EXISTS(SELECT 1 FROM invoices WHERE id=?)", (self.id, ))
fetched = response.fetchone()[0]
if fetched == 1:
    print("Exist")
else:
    print("Does not exist")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM