Search code examples
pythonmysql-pythoncontrol-flow

Comparing MySQL table record with user entered value in PYTHON


Here I'm basically trying to fetch a string value from the SQL Table and I want to compare that value with the string I entered. I tried this simple way but unfortunately, it isn't working. I need help.CurrentOutput

def cantkt():
    #tkt()
    #canstate=("DELETE FROM Chart WHERE PNR=%s"%canpnr)
    canpnr=input("Enter PNR No. to Cancel Ticket: ")
    mycsr.execute("SELECT PNR FROM Chart WHERE PNR=%s"%canpnr)
    res=mycsr.fetchone()
    print(res)
    if res==canpnr:
         print("PNR MATCHED")
    else:
         print("PNR No. DOES NOT MATCH")

Solution

  • as you can see in the print, the result of the fetching is a tuple, not a string.

    You can do simply this:

    res = mycsr.fetchone()
    if res: res = res[0]
    

    Explanation:

    res is ('1019654419', ) so you must seek the value you want to get, in this case the first one.

    In "if res: res = res[0]" we check if res has a value because in case the ticket does not exist the fetching value would be an empty tuple, so trying to get the first result will raise an IndexError.