Python Forum
IndexError: list index out of range
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IndexError: list index out of range
#1
Hello, I need help, I had a goal to make a bot that would work with a database on SQLITE3, everything was connected, but in the process of interacting with the bot, an error occurs.All files that are used in the process are attached.


Error:
return int(result[0][0]) IndexError: list index out of range
Code file db.py:
import sqlite3

class Database:
    def __init__(self, db_file):
        self.connection = sqlite3.connect(db_file)
        self.cursor = self.connection.cursor()

    def user_exists(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT * FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            return bool(len(result))

    def add_user(self, user_id):
        with self.connection:
            self.cursor.execute("INSERT INTO 'users' ('user_id') VALUES (?)", (user_id,))

    def user_money(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT 'money' FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchmany(1)
            return int(result[0][0])
code file main.py
import logging
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types.message import ContentTypes
from db import Database

import config as cfg
import markups as nav

logging.basicConfig(level=logging.INFO)

bot = Bot(token=cfg.TOKEN)
dp = Dispatcher(bot)

db = Database('database.db')

@dp.message_handler(commands=['start'])
async def start(message: types.Message):
    if message.chat.type == 'private':
        if not db.user_exists(message.from_user.id):
            db.add_user(message.from_user.id)

        await bot.send_message(message.from_user.id, f"Welcome user!\n Balance:{db.user_money(message.from_user.id)}$")


if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)

Attached Files

.zip   database.zip (Size: 403 bytes / Downloads: 112)
.py   main.py (Size: 723 bytes / Downloads: 106)
.py   db.py (Size: 1.01 KB / Downloads: 107)
Reply
#2
IndexError: list index out of range
    def user_money(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT 'money' FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchmany(1)
            return int(result[0][0])
First test result for length to see if anything was retrieved. Second, print result to see if/what result[0][0] would be.
rob101 and BashBedlam like this post
Reply
#3
Why are you using quotes inside your queries?

I expect a query to be formatted like this:
result = self.cursor.execute("SELECT money FROM users WHERE user_id = ?", (user_id,)).fetchmany(1)
I guess you can make a table where all the columns have starting and ending quotes, but why?

And why are you using fetchmany(1) instead fetchone()?
return self.cursor.execute("SELECT money FROM users WHERE user_id = ?", (user_id,)).fetchone()
dolac likes this post
Reply
#4
(Jul-25-2022, 05:00 AM)deanhystad Wrote: Why are you using quotes inside your queries?

I expect a query to be formatted like this:
result = self.cursor.execute("SELECT money FROM users WHERE user_id = ?", (user_id,)).fetchmany(1)
I guess you can make a table where all the columns have starting and ending quotes, but why?

And why are you using fetchmany(1) instead fetchone()?
return self.cursor.execute("SELECT money FROM users WHERE user_id = ?", (user_id,)).fetchone()

Thanks, it was all about the quotes that were in the db.py file.
Reply
#5
Quote:Thanks, it was all about the quotes that were in the db.py file.
Huh? That is not and answer to "Why are you using quotes inside your queries?" Do you mean that the quotes in the queries were the reason why you got an index error?

Even if your code works now, indexing should always be checked or protected to prevent an empty reply from crashing your program.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  IndexError: index 10 is out of bounds for axis 0 with size 10 Mehboob 11 1,952 Sep-14-2023, 06:54 AM
Last Post: Mehboob
Thumbs Down I hate "List index out of range" Melen 20 3,161 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 5,968 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  I'm getting a String index out of range error debian77 7 2,280 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,410 May-03-2022, 01:39 PM
Last Post: Anldra12
  TypeError: list indices must be integers or slices, not range Anldra12 2 2,501 Apr-22-2022, 10:56 AM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,111 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,762 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,239 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  IndexError: list index out of range Laplace12 1 2,186 Jun-22-2021, 10:47 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020