Python检查sqlite数据出口



我写了几行代码来检查数据库中是否存在数据,如下所示:

def check_if_data_exists(self):
with self.connection as mycur:
result = mycur.execute(f'select 1 from Summary1 where "Date Time" = "20220722.2008";')
for row in result:
if row == (1,):
print("yes its here")

当数据存在时;是的,就在这里;。然而,如果我这样写行:

def check_if_data_exists(self):
with self.connection as mycur:
result = mycur.execute(f'select 1 from Summary1 where "Date Time" = "20220723.2008";')
for row in result:
if row == (1,):
print("yes its here")
else:
print("No its not here")

它无法打印";不,它不在这里;。相反,程序只是在没有发生任何事情的情况下运行。顺便说一句,我在用Pycharm。

有人知道发生了什么事吗?请问我怎样才能得到假条件结果?

或者,任何更好的代码实现相同结果的更好方式都将受到赞赏。

非常感谢。

这里发生的情况是,如果找不到匹配的数据,则结果集为空,因此返回的列表将完全为空,并且也是错误的。尝试使用此版本:

def check_if_data_exists(self):
with self.connection as mycur:
result = mycur.execute("SELECT 1 FROM Summary1 WHERE "Date Time" = '20220723.2008'")
if result:
print("yes its here")
else:
print("No its not here")

也许更安全的方法是使用exists查询,然后只检查返回的(单个(布尔值:

def check_if_data_exists(self):
with self.connection as mycur:
mycur.execute("SELECT EXISTS (SELECT 1 FROM Summary1 WHERE "Date Time" = '20220723.2008')")
row = mycur.fetchone()
if row[0]:
print("yes its here")
else:
print("No its not here")

在上面的第二个版本中,您总是会返回一个具有单个记录和布尔值的结果集。

最新更新