简体   繁体   English

Python 检查 SQLite3 中是否存在

[英]Python check if exists in SQLite3

I'm trying to check whether a variable exists in an SQLite3 db.我正在尝试检查 SQLite3 数据库中是否存在变量。 Unfortunately I can not seem to get it to work.不幸的是,我似乎无法让它工作。 The airports table contains 3 colums, with ICAO as the first column.机场表包含 3 列,ICAO 作为第一列。

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?这段代码有什么问题?

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. cursor.execute返回值是游标(或者更准确地说是对自身的引用)并且与查询结果无关。 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.另一方面,如果您调用cursor.fetchone结果元组或 None 如果没有通过查询条件的行。 So in your case if c.fetchone(): would mean one of the below:所以在你的情况下, if c.fetchone():意味着以下之一:

if (1, ):
    ...

or要么

if None:
    ...

Let's prepare a database to test it.让我们准备一个数据库来测试它。

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'))

Since your SELECT 1 FROM airports WHERE ICAO = 'EHAM' already serves the purpose of checking existence, let's use it directly, without the redundant SELECT EXISTS()由于您的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...")

the result is结果是

Found!

Let's check a non-existent case让我们检查一个不存在的案例

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

the result is结果是

Not found...

If you just want to fix your code, you can try如果你只是想修复你的代码,你可以试试

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

the result is结果是

Found!

Thanks for the answer from zero323, although the code snippet is wrong, as fetchone() does not return True or False.感谢 zero323 的回答,尽管代码片段是错误的,因为fetchone()不返回 True 或 False。 It only returns 1 for True and 0 for False.它只为 True 返回 1,为 False 返回 0。 (binary) The following code works without problems in Python3: (二进制)以下代码在 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