[英]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. 然后我需要检查MySQL,如果我已经创建的表包含该特定对。 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? 我应该在python中写一个语句来检查我所获取的数据是否为空集,使用“except”关键字告诉用户该特定对的条目不存在?
I don't know how to use the "except" keyword. 我不知道如何使用“except”关键字。 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. 假设用户输入“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])
If 'P' does not contain anything, how do I notify the user that the particular pair does not exist? 如果'P'不包含任何内容,如何通知用户特定对不存在?
Use RowCount
property to see how many rows are returned. 使用RowCount
属性查看返回的行数。 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 : 一般来说,以下是检查是否有任何对象为null的方法:
if foo is None:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.