PYMYSQL“fetchone()是否为None”等同于fetchall()?

2024-05-03 11:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

当用户输入ID修改销售时,我需要控制空记录

这里有一个技巧,如果我将cursor.fetchone()而不是cursor.fetchall(),条件为None将验证行是否为空,并告诉用户输入另一个ID,但它似乎根本无法使用fetchall()

我必须使用fetchall,否则我将开始在prettytable格式上出现问题

consulta = "SELECT id, CAST(fecha AS CHAR), id_cliente, total FROM compra WHERE id = %s;"
                cursor.execute(consulta, (id))
                compra = cursor.fetchall()
                **if (compra is None):**
                    print("ID is not valid.\n")
                    exito = False
                    return
                else:
                    exito = True
                T.clear_rows()
                for x in compra:
                    T.add_row(x)
                clear()
                print(T)

提前谢谢


Tags: 用户noneid技巧is记录cursorprint
1条回答
网友
1楼 · 发布于 2024-05-03 11:43:37

Python DB API定义fetchall返回某种序列,不管结果中可能有多少行。其中fetchone返回None在未找到行的事件中,fetchall返回空序列。如果您的特定库返回列表,您可以轻松检查列表是否为空:

compra = cursor.fetchall()
if not compra:
    print("ID is not valid")
    return

如果它返回其他类型的惰性迭代器,您可能无法在不尝试对其进行迭代的情况下判断它是否为空。你可能需要像这样的东西

compra = cursor.fetchall()
try:
    first = next(compra)
except StopIteration:
    print("ID is not valid.")
    return
T.clear_rows()
T.add_row(first)
for x in compra:
    T.add_row(x)

根据T是什么以及在确定compra是否为空之前调用T.clear_rows()是否安全,可能有一个更简单的解决方案

相关问题 更多 >