Python + MariaDB skipping else statement

Viewed 24

I'm trying to use Python to record barcodes scanned for manifesting parcels. I want to use OpenCV ultimately as the input but don't want to limit its number of scans per parcel so I want to test to see if a parcel has already been marked as shipped in MariaDB.

The input works (from a handheld scanner for now) and it is looking up against the DB to see if the barcode has been scanned before fine, but when it comes to one that hasn't, it seems to skip the else statement. I've been staring at this code for ages now! Any help appreciated. Thanks

import mariadb
import sys

from datetime import datetime
now  = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)

conn = mariadb.connect(
    user="root",
    password="password",
    host="localhost",
    database="pythontest")
cur = conn.cursor()

while True:
    barcode=input("--->  ")
    if barcode.startswith("%"):
        courier = ("DPD")
    elif barcode.startswith("JD"):
        courier = ("Royal Mail")
    else:
        courier = ("Unknown Courier")
        print("Unknown Courier")
    cur.execute("SELECT trackingNumber,status,shipTime,courier FROM opencvdb WHERE trackingNumber=?", (barcode,))
    for trackingNumber, status, shipTime, courier in cur:
        if trackingNumber in barcode:
            print(f"Already Shipped at {shipTime} with {courier} - Tracking Number: {barcode}")
        else:
            try:
                print("Shipping Now")
                cur.execute("INSERT INTO opencvdb (trackingNumber,status,shipTime,courier) VALUES (?, ?, ?, ?)", (barcode, "Done", dt_string,courier))
            except mariadb.Error as e:
                print(f"Error: {e}")

            conn.commit()
            print(f"Last Inserted ID: {cur.lastrowid}")

conn.close()
1 Answers

if this query doesn't return any results (because there are no matching records)

cur.execute("SELECT trackingNumber,status,shipTime,courier FROM opencvdb WHERE trackingNumber=?", (barcode,))

then this for statement has nothing to loop over

for trackingNumber, status, shipTime, courier in cur:

And this statement is never executed

if trackingNumber in barcode:

UPDATE: I think this is probably what you want to do:

cur.execute("select...")
found = False
for (trackingNumber, status....) in cur.fetchall():
    found = True
    print("Already shipped...")

if not found:
    cur.execute("insert into....")
    conn.commit()
Related