Python 当MS SQL表中不包含数据时,如何防止“非类型”对象不可下标错误?
当前,如果搜索MS SQL表中不存在的数据,我会收到一个非类型的“object is not subscriptable error”。 与其停止Python并输出此错误,我只希望它声明“数据不存在”并请求另一次搜索 这是我目前的代码:Python 当MS SQL表中不包含数据时,如何防止“非类型”对象不可下标错误?,python,sql,sql-server,python-3.x,pypyodbc,Python,Sql,Sql Server,Python 3.x,Pypyodbc,当前,如果搜索MS SQL表中不存在的数据,我会收到一个非类型的“object is not subscriptable error”。 与其停止Python并输出此错误,我只希望它声明“数据不存在”并请求另一次搜索 这是我目前的代码: cursor = connection.cursor() SQLCommand = ("SELECT Name, Location_ID " "FROM dbo.PB_Location " "WHERE Location_ID =
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.PB_Location "
"WHERE Location_ID = ?")
Values = [choice]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
os.system('cls' if os.name == 'nt' else 'clear')
# note: UID column is an integer. You can't normally take an integer and place it in a string.
# so you must add str(results[2])
print (" ")
print("Name: " + results[0] + " Location ID: " + str(results[1]))
connection.close()
下面的内容不起作用,但我能做些类似的事情吗
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.PB_Location "
"WHERE Location_ID = ?")
Values = [choice]
cursor.execute(SQLCommand,Values)
while True:
results = cursor.fetchone()
if results is None:
break
os.system('cls' if os.name == 'nt' else 'clear')
# note: UID column is an integer. You can't normally take an integer and place it in a string.
# so you must add str(results[2])
print (" ")
print("Name: " + results[0] + " Location ID: " + str(results[1]))
connection.close()
哦,我知道了
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.PB_Location "
"WHERE Location_ID = ?")
Values = [choice]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
if results:
os.system('cls' if os.name == 'nt' else 'clear')
print (" ")
print ("Name: " + results[0] + " Location ID: " + str(results[1]))
connection.close()
else:
print (" Does not exist.")
connection.close()