Search code examples
pythonfetchpymysql

PYMYSQL "fetchone() is None" equivalent to fetchall()?


I need to control empty records when the user enters ID to modify a sale.

Here is the trick, if I put cursor.fetchone() instead of cursor.fetchall(), the condition is None validates that the row is empty, and tells the user to enter another ID, but it doesnt seem to work with fetchall() at all.

I must use fetchall, otherwise Ill start having problems with prettytable format.

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)

Thanks in advance!


Solution

  • The Python DB API defines fetchall to return a sequence of some kind, no matter how many rows may be in the result. Where fetchone returns None in the event no row is found, fetchall returns an empty sequence. If your particular library returns a list, you can easily check if the list is empty:

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

    If it returns some other kind of lazy iterator, you may not be able to tell if it is empty without at least trying to iterate over it. You may need something like

    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)
    

    There may be a simpler solution, depending on what T is and whether it is safe to call T.clear_rows() before determining if compra is empty.