P
P
pypyshka2016-07-01 12:17:29
Python
pypyshka, 2016-07-01 12:17:29

How to get around error when searching in SQLite database?

Good afternoon. I'm learning Python 3.5.1 and SQLite 3. There is a test
table in the database with the entry: id | data1 | 123 I am trying to search this database:

text = ['123, '456']
sql = """SELECT * FROM test WHERE data LIKE (?)"""
try:
    for i in text:
                cur.execute(sql, [(i),])
                result = cur.fetchone()[1]
                if i == result:
                    print("Найдено.")
                else:
                    print("Не найдено.")
except TypeError as err:
    print("Ошибка: ", err)
else:
    print("Готово.")

When searching for the value "123", it displays "Found.", but when it comes to the value "456", the error 'NoneType' object is not subscriptable , as it is not in the database, occurs. Tell me, please, is it possible to skip a value that is not in the database and complete the loop, That is, for example:
Check: "123"
Output: "Found."
Check: "456"
Output: "Not found."
We are looking for further values, if there are none, then we display "Done."

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DDDsa, 2016-07-01
@pypyshka

You can, for example, first check the number of records returned

if cur.rowcount > 0:
    result = cur.fetchone()[1]
    print('Найдено')
else:
    print('Не найдено')

By the way, your LIKE will only output exact matches. If you want to enter "12" and search for the string "123", then nothing will be found, you need to use LIKE %[search_string]%. Only in this case will you have to say goodbye to convenient substitution through (?)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question