Home > OS >  IndexError: tuple index out of range Mysql
IndexError: tuple index out of range Mysql

Time:08-16

Hello everyone I'm trying to write a telegram bot that can delete code from a Mysql database. I still can't solve the problem that I have. The code that I need to check is stored in the "item" variable, but when I do the check, it writes to me: if check_code[0][0] == item: IndexError: tuple index out of range. Please help solve this problem! I just started programming in this cool language!

@dp.message_handler(state=dataBase.user1)
async def user_code(message: types.Message, state: FSMContext):
    item = message.text
    await state.update_data(
        {
            'item': item
        }

    )
    data = await state.get_data()
    item = data.get('item')
    if len(item) == 0:
        return
    cursor.execute(f'DELETE FROM users WHERE code="{item}"')
    check_code = cursor.fetchall()
    if check_code[0][0] == item:
        await bot.send_message(message.from_user.id,"The user has been successfully deleted!")
    else:
        await bot.send_message(message.from_user.id, "There is no such user!")


    await state.finish()

CodePudding user response:

.fetchall() method will return a list of tuples for the table you are querying. In this case, your query deletes the records so it is possibly returning an empty tuple. You need a SELECT query for fetchall() to return any results. If you want to see if the record was successfully deleted, you can run the following after the delete query:

cursor.execute(f'SELECT * FROM users WHERE code="{item}"')
check_code = cursor.fetchall()

If this doesn't return anything, then you know that the record was deleted.

  • Related