首页 > 解决方案 > 如何在从mysql数据库中获取数据到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”不包含任何内容,我如何通知用户该特定对不存在?

标签: pythonmysqldatabaseexcept

解决方案


使用RowCount属性查看返回了多少行。例子 :

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

一般来说,以下是检查任何对象是否为 null 的方法:

if foo is None:

推荐阅读