首页 > 解决方案 > 无法访问元组的索引。IndexError:列表索引超出范围

问题描述

我在 python 中使用 sqlite3 创建了一个数据库,然后添加了一个包含 5 个参数的表。我在表格中添加了一个条目,填充了所有 5 个参数。我正在尝试选择具有特定参数“用户”的所有条目。

如果我打印没有索引的选定元组,它将按预期返回一个具有 5 个参数的元组。

如果我打印索引为 [0] 的元组,它会返回一个包含 5 个参数的元组,而不仅仅是第一个参数。

如果我打印索引高于 [0] 的条目,例如 [1],它会返回IndexError: list index out of range。

我想访问所有索引,但除了我尝试过的方法之外,我不知道该怎么做。

下面的代码:(financedb 是我的另一个 .py 文件,其中包含一个db_connect()连接到数据库的函数。我在下面的代码中包含了该函数,以便更容易复制代码。)

import sqlite3
import financedb as fdb

user_name_input = input('Username: ')


def check_the_balance():

    fdb.db_connect() # Establishes connection to DB

    fdb.cursor.execute('SELECT * FROM test WHERE user=?', [user_name_input])
    check = fdb.cursor.fetchall()
    print(check[0])

def db_connect():

    global connection 
    global cursor 

    cursor = connection.cursor()
    command = f'CREATE TABLE test(id integer, user text, password text, montly_income real, monthly_debt real)'

    try:
        cursor.execute(command)

    except sqlite3.OperationalError:
        pass

    finally:
        connection.commit()
check_the_balance()  

标签: pythonsqlitetuples

解决方案


.fetchall返回一个行列表,所以我假设你想要check[0][0]? 这可能会给你你想要的:

def check_the_balance():

    fdb.db_connect() # Establishes connection to DB

    fdb.cursor.execute('SELECT * FROM test WHERE user=?', [user_name_input])
    for items in fdb.cursor.fetchall():
        print(items)
        print(items[0])

推荐阅读