A
A
Asriel2021-06-26 20:49:35
Python
Asriel, 2021-06-26 20:49:35

How to write data to database?

Hello. I'm making a Telegram bot using TelegramBotApi. I want to write id and username to SQLite database. But I also want to make a condition that if this user is in the database, then it does not need to be written down. I don't know how to implement it correctly.

Where to get id and username I know

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2021-06-27
@o5a

Add a constraint on the uniqueness of this field, then when adding a record, it will be possible to automatically skip adding if a conflict occurs (duplicating records). The specific format depends on the database. For sqlite:
add unique(field name) to table creation

create table mytable (id integer primary key,
user_id integer,
....,
unique(user_id)
)

then when inserting data
INSERT INTO mytable (user_id, user_name) VALUES (...) ON CONFLICT(user_id) DO NOTHING

It is possible and more crutch variant. Make a query before inserting data
result = cur.execute('select 1 from mytable where user_id = ?), (user_id, )).fetchone()
if not result:
   # делаем insert

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question