繁体   English   中英

在从mysql数据库中获取数据到python时如何编写用于检查空集的语句?

[英]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.

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