V
V
Voldemar212021-12-05 23:14:28
Python
Voldemar21, 2021-12-05 23:14:28

Why does it give an error about the wrong number of bindings?

Faced this error:

Incorrect number of bindings supplied. The current statement uses 3, and there are 2 supplied.

The question is why, what is the reason and how it is solved. It throws an error on this line:

self.cursor.execute('INSERT INTO `task_list` (`users_id`, `date`, `task`) VALUES (?, ?, ?)', (self.get_user_id(user_id), tuple(data.values())))

But if you remove this argument self.get_user_id(user_id), then everything is written to the database normally, with the exception of user_id. I just need to implement writing to the second user_id table from the first table.

Database class code
import sqlite3


class DBot:
    def __init__(self, database):
        self.connection = sqlite3.connect(database)
        self.cursor = self.connection.cursor()
        if self.connection:
            print ("База данных подключена")
    # Проверяем, есть ли уже юзер в базе
    def user_exists(self, user_id):
            result = self.cursor.execute("SELECT `id` FROM `user` WHERE `user_id` = ?", (user_id,))
            return bool (len(result.fetchall()))
    # Достаем id в базе данных по его user_id
    def get_user_id (self, user_id):
            result = self.cursor.execute("SELECT `id` FROM `user` WHERE `user_id` = ?", (user_id,))
            return result.fetchone()[0]
    #Добавляем юзера в базу
    def add_user(self, user_id):
        self.cursor.execute("INSERT INTO `user` (`user_id`) VALUES (?)", (user_id,))
        return self.connection.commit()
    # Создаем запись в task_list о полученных задачах
    #staticmethod
    async def sql_add_command (self, user_id, state):
        async with state.proxy() as data:
            #tasks = ((self.get_user_id(user_id)), (data.values()),)
            #self.cursor.execute('INSERT INTO `task_list` (`users_id`, `date`, `task`)VALUES (?, ?, ?)', (self.get_user_id(user_id), tuple(data.values())),)
            self.cursor.execute('INSERT INTO `task_list` (`users_id`, `date`, `task`) VALUES (?, ?, ?)', (self.get_user_id(user_id), tuple(data.values())))
            return self.connection.commit()
    def close(self):
        """Закрываем соединение с БД"""
        self.connection.close()

State machine code on aiogram
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram import types, Dispatcher
from aiogram.types import message
from aiohttp.helpers import current_task
from config import bot, dp
from aiogram.dispatcher.filters import Text
from bot import DBot
from client_kb import kb_client



@dp.message_handler(commands=['start', 'help'])
async def command_start (message: types.Message):
    if (not DBot.user_exists(message.from_user.id)):
        DBot.add_user(message.from_user.id)
    await bot.send_message(message.from_user.id, "Добрый день", reply_markup=kb_client)

class FSAdmin(StatesGroup):
    dates = State()
    task = State()


# Выход из состояний
@dp.message_handler(state="*", commands="отмена")
@dp.message_handler(Text(equals="отмена", ignore_case=True), state="*")
async def cancel_handler(message: types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return
    await state.finish()
    await message.reply("Отменено")


# Начало диалога с пользователем
@dp.message_handler(commands="добавить_задачу")
async def cm_start(message: types.Message):
        await FSAdmin.dates.set()
        await message.reply("Укажите дату")

# Ловим дату задачи
@dp.message_handler(state=FSAdmin.dates)
async def load_dates(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
            data["data"] = message.text
    await FSAdmin.next()
    await message.reply ("Введите описание задачи")

# Ловим состав задачи
@dp.message_handler(state=FSAdmin.task)
async def load_task(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
            data["task"] = message.text
            await message.reply ("Задача сохранена")

    await DBot.sql_add_command(message.from_user.id, state)
    await state.finish()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-12-05
@voldemar21

Everything is logical, you are trying to transfer two values ​​​​to the three fields user_id, data and task - something returned by the self.get_user_id(user_id) method call and a tuple from data.values().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question