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: 18)
.py   main.py (Size: 723 bytes / Downloads: 17)
.py   db.py (Size: 1.01 KB / Downloads: 17)
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.
BashBedlam and rob101 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
  I'm getting a String index out of range error debian77 7 604 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 584 May-03-2022, 01:39 PM
Last Post: Anldra12
  TypeError: list indices must be integers or slices, not range Anldra12 2 717 Apr-22-2022, 10:56 AM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 1,367 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 1,441 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 1,117 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  IndexError: list index out of range Laplace12 1 1,457 Jun-22-2021, 10:47 AM
Last Post: Yoriz
  IndexError: list index out of range brunolelli 11 3,604 Mar-25-2021, 11:36 PM
Last Post: brunolelli
  index of range, but data prints out mrc06405j 1 1,374 Mar-25-2021, 07:20 PM
Last Post: buran
  Changing Index of 2 List in python giddyhead 0 1,061 Mar-05-2021, 05:45 PM
Last Post: giddyhead

Forum Jump:

User Panel Messages

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