简体   繁体   中英

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

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM