How to write statement for checking empty set while fetching data from mysql database into python?

by Ansh Aggarwal   Last Updated June 13, 2019 08:26 AM

I need to take entries from the user about "from" and "where to" of their bus route. Then I need to check in MySQL if my already-created table contains that particular pair. What should I write as a statement in python to check if the data I have fetched is an empty set using "except" keyword to tell the user that entry of that particular pair does not exist?

I don't know how to use the "except" keyword. Suppose the user enters "from-Delhi" and "where to-Rajasthan" , and the particular entry does to exist in my table, I want to know the python statement/code I should write so that the user will know that it is not there.

import MySQLdb
def passenger():
    db=MySQLdb.connect(host="localhost",port=3306,user="root",passwd="",db="superprogram")
    cur=db.cursor()                                     #connected with MySQL
    num=int(input('''Enter 1 to book tickets
    Enter 2 to cancel tickets
    Enter 3 for enquiry panel-'''))
    if num==1:
        start=input("Enter the name of your state-")        #where you live
        dest=input("Enter your destination-")              #your destination
        start.capitalize()
        dest.capitalize()               #because MySQL entries are capital
        s="select * from businfo where Point_Of_Departure='"+start+"' and Destination='"+dest+"'"
        cur.execute(s)
        P=cur.fetchall()
        for i in P:                                 #if entry exists
             if i[6]>0:                              #if there are seats left
                print("Bus ID-",i[1])
                print("Point Of Departure-",i[2])
                print("Destination-",i[3])

If 'P' does not contain anything, how do I notify the user that the particular pair does not exist?



Answers 1


Use RowCount property to see how many rows are returned. Example :

cur.execute(s)
numRows = cur.rowcount
if numRows == 0:
    # pair does not exist

Generally speaking, following is the way to check if any object is null :

if foo is None:
Sukhi
Sukhi
June 13, 2019 08:25 AM

Related Questions


Updated August 13, 2017 09:26 AM

Updated July 11, 2015 15:11 PM

Updated September 28, 2017 07:26 AM

Updated July 28, 2018 14:26 PM