Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当MS SQL表中不包含数据时,如何防止“非类型”对象不可下标错误?_Python_Sql_Sql Server_Python 3.x_Pypyodbc - Fatal编程技术网

Python 当MS SQL表中不包含数据时,如何防止“非类型”对象不可下标错误?

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 =

当前,如果搜索MS SQL表中不存在的数据,我会收到一个非类型的“object is not subscriptable error”。 与其停止Python并输出此错误,我只希望它声明“数据不存在”并请求另一次搜索

这是我目前的代码:

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()