[英]How to write statement for checking empty set while fetching data from mysql database into python?
我需要從用戶那里獲取關於他們的公共汽車路線的“從”和“在哪里”的條目。 然后我需要檢查MySQL,如果我已經創建的表包含該特定對。 我應該在python中寫一個語句來檢查我所獲取的數據是否為空集,使用“except”關鍵字告訴用戶該特定對的條目不存在?
我不知道如何使用“except”關鍵字。 假設用戶輸入“from-Delhi”和“where to-Rajasthan”,並且特定條目確實存在於我的表中,我想知道我應該寫的python語句/代碼,以便用戶知道它不是那里。
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])
如果'P'不包含任何內容,如何通知用戶特定對不存在?
使用RowCount
屬性查看返回的行數。 示例:
cur.execute(s)
numRows = cur.rowcount
if numRows == 0:
# pair does not exist
一般來說,以下是檢查是否有任何對象為null的方法:
if foo is None:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.