J
J
James_Obry2021-11-01 00:32:37
Python
James_Obry, 2021-11-01 00:32:37

How to "correctly" check for the existence of a record in a SQLite3 table?

Hello, I have a question how to correctly check the existence of a record in a SQLite3 database table.
You can do this:
def check_exist():

with sq.connect(database_path) as con:
        cur = con.cursor()
        my_id = 'любой id' # переменная хранящая id записи нужного пользователя
        author_ids = [x[0] for x in cur.execute("select id from authors").fetchall()] # массив с id записей
        if my_id in author_ids:
            print('+')
        else:
            print('-')

But if there are many records in the table, then the code will slow down

. You can also do this:
def check_exist():
    try:
        with sq.connect(database_path) as con:
            cur = con.cursor()
            my_id = 'любой id' # переменная хранящая id записи нужного пользователя
            author_ids = cur.execute(f"select id from authors where id = '{my_id}'").fetchone()[0]
            print('+')
    except:
        print('-')


In any case, the code is not very good. Can you please tell me how to do this check?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-11-01
@vabka

But if you started with SQL, but knew that there is an EXISTS operator

SELECT EXISTS(SELECT * FROM authors where id = ?) -- Вернёт true, если какие-то записи по запросу находятся

And if there is an index on the required field, then there should be no problems with speed.
The index is created using the CREATE INDEX query:
https://www.sqlite.org/lang_createindex.html

P
Python Newbie, 2021-11-01
@Levman5

cursor.execute("SELECT id FROM authors WHERE id = ?", (my_id ))
if cursor.fetchone() is None:
    # Если нету записи то код

Like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question