How to check if the user id is in the database so that it does not write again? Those. if there is, then do not write, if not, then enter the data. The code works, but it remains only to write a check. I believe that

cursor.execute ("SELECT * FROM stats WHERE userid =?", (userid))

result = cursor.fetchone ()

but you still need to add and where to put to check. I hope that explained clearly (I am learning). Here is the whole code:

import telebot import const import time import random from keyboards import * import sqlite3 bot = telebot.TeleBot(const.token) conn = sqlite3.connect("mybase.db") cursor = conn.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS stats (id INT, username VARCHAR, name VARCHAR, surname VARCHAR)") conn.commit() conn.close() @bot.message_handler(commands=['start']) def start(message): userid = message.from_user.id username = message.from_user.username user_name = message.from_user.first_name user_surname = message.from_user.last_name conn = sqlite3.connect("mybase.db") cursor = conn.cursor() cursor.execute("INSERT INTO stats VALUES (?, ?, ?, ?)", (userid, username, user_name, user_surname)) conn.commit() my_id = 410924655 if userid == my_id: bot.send_message(message.chat.id, 'Привет, Хозяин!', reply_markup=menu) time.sleep(1) bot.send_message(message.chat.id, 'Выбери нужный пункт:', reply_markup=admenu) else: bot.send_message(message.chat.id, 'Привет, ' + message.from_user.first_name + '!', reply_markup=menu) time.sleep(1) bot.send_message(message.chat.id, 'Нажми кнопку "Задать вопрос" и произнеси вопрос.\nШар ответит тебе через 5 секунд.', reply_markup=quest) conn.close() @bot.message_handler(content_types=['text']) def message(message): if message.text == 'Реклама в боте': bot.send_message(message.chat.id, 'Чтобы ознакомиться с прайсом и заказать рекламу напишите нам 👉🏼 @мой акк', reply_markup=quest) elif message.text == 'Тех. поддержка': bot.send_message(message.chat.id, 'Если у вас есть какой-то вопрос, пожелания и предложения, то напишите нам 👉🏼 @мой акк', reply_markup=quest) else: bot.send_message(message.chat.id, message.from_user.first_name + ', я всего лишь бот. Может быть у тебя есть какой-то вопрос?', reply_markup=quest) @bot.callback_query_handler(func=lambda call: True) def ques(call): if call.data == 'quest1': bot.send_message(call.message.chat.id, 'Произнесите вопрос') o = random.choice(const.otvet) time.sleep(5) bot.send_message(call.message.chat.id, o) time.sleep(1) bot.send_message(call.message.chat.id, 'Может быть у вас есть еще вопрос?', reply_markup=quest) elif call.data == 'stat': conn = sqlite3.connect("mybase.db") cursor = conn.cursor() cursor.execute("SELECT COUNT(*) FROM stats") r = cursor.fetchall() bot.send_message(call.message.chat.id, f'Всего пользователей: {r[0][0]}') conn.close() if __name__ == 'main': print('Bot has been started...') bot.polling(none_stop=True, interval=0) 

    1 answer 1

    First, make id primary key. Secondly, INSERT OR IGNORE INTO stats VALUES (?, ?, ?, ?) .

    • Then, mb and add an example - id INTEGER PRIMARY KEY ? :) - gil9red
    • why do i need a primary key? As I understand it is a sequence number, but I need user id. Total I get "SELECT COUNT (*) FROM stats" - Yuri Popov
    • @YuriyPopov so that OR IGNORE works and it was possible not to make unnecessary requests to the database, especially as slow as COUNT . However, you can do without the restriction of uniqueness on the id field. - Sergey Gornostaev