0

Currently I get a ''NoneType' object is not subscriptable error' if I search for data that is not in the MS SQL table. Instead of stopping Python and outputting this error, I just want it to state that the 'data does not exist' and request another search.

Here is my current code:

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

The below doesn't work, but would I do something close to this?

    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()
Prox
  • 699
  • 5
  • 11
  • 33

1 Answers1

1

Oh, I figured it out...

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()
Prox
  • 699
  • 5
  • 11
  • 33