Ошибка с добавлением в БД sqlite3

System

Новичок
Пользователь
Мар 11, 2022
14
0
1
Написал простенький бот, чтобы протестить саму БД и наткнулся на ошибку:
Только один человек может попасть в саму БД
ViDYEK6.png

А когда кто-то ещё хочет попасть в таблицу, то он уже там "есть" под chat_id другого человека
tea2kof.png


Сам код:
Python:
import telebot
import config

from database import Database
from telebot import types

bot = telebot.TeleBot(config.TOKEN)
db = Database('sosi.db')

@bot.message_handler(commands = ['add'])
def adduser(message):
    if not db.check_user(message.from_user.id,):
        db.add_user(message.from_user.id,message.from_user.username,)
        bot.send_message(message.chat.id, 'Вас добавили в БД.')
    else:
        bot.send_message(message.chat.id, 'Не-а.')

@bot.message_handler(commands = ['remove'])
def removeuse(message):
    if db.check_user(message.from_user.id):
        db.remove_user(message.from_user.id,message.from_user.username,)

@bot.message_handler(content_types = ['text'])
def start(message):
    if db.check_user(message.from_user.id):
        bot.send_message(message.chat.id, message.text)
    else:
        bot.send_message(message.chat.id, '222222')

bot.polling(none_stop = True)
БД:
Python:
import sqlite3

class Database:
    def __init__(self, database_file):
        self.connection = sqlite3.connect(database_file, check_same_thread = False)
        self.cursor = self.connection.cursor()

    def check_user(self, chat_id):
        with self.connection:
            result = self.cursor.execute("SELECT `chat_id` FROM `userchat` ").fetchmany(1)
            return bool(len(result))

    def add_user(self, chat_id, username):
        with self.connection:
            return self.cursor.execute("INSERT INTO `userchat` (`chat_id`, `username`) VALUES (?,?)", (chat_id, username,))

    def remove_user(self, chat_id, username):
        with self.connection:
            return self.cursor.execute("DELETE FROM `userchat` WHERE `chat_id` = ? AND `username` = ?",(chat_id,username,)).fetchmany(1)

    def select_user(self, chat_id):
        with self.connection:
            return self.cursor.execute("SELECT `chat_id` FROM `userchat` ").fetchall()

Хотелось бы узнать как решить проблему, код написал для теста
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 587
459
83
fetchmany(1) возвращает вам одну запись, значит в result что то есть, и функция check_user всегда возвращает true
 

Форум IT Специалистов