Answer the question
In order to leave comments, you need to log in
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('-')
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('-')
Answer the question
In order to leave comments, you need to log in
But if you started with SQL, but knew that there is an EXISTS operator
SELECT EXISTS(SELECT * FROM authors where id = ?) -- Вернёт true, если какие-то записи по запросу находятся
cursor.execute("SELECT id FROM authors WHERE id = ?", (my_id ))
if cursor.fetchone() is None:
# Если нету записи то код
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question