python - 如何在从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”不包含任何内容,我如何通知用户该特定对不存在?
解决方案
使用RowCount
属性查看返回了多少行。例子 :
cur.execute(s)
numRows = cur.rowcount
if numRows == 0:
# pair does not exist
一般来说,以下是检查任何对象是否为 null 的方法:
if foo is None:
推荐阅读
- security - 具有桌面应用程序安全性的 OAuth2
- r - 通过对某些列求和并保留其余列来对数据进行分组
- java - GUI 外的 ClickListener
- html - 模态对话框关闭图标与 CSS 对齐
- python - 使用同一张表的 2 个外键后迁移时出错
- python - UnicodeDecodeError:“ascii”编解码器无法解码位置 2 中的字节 0xc3:序数不在范围内(128)
- bots - Cisco spark(现为 Webex 团队)Bot 是否有丰富的卡片支持
- c++ - atomic_thread_fence 的范围是什么?
- python - 优化幂集的搜索
- python - 为什么 vue-resource 不在 XHR 中发送 cookie,所以会话不起作用?