简体   繁体   English

无法访问元组的索引。 IndexError:列表索引超出范围

[英]Can't access index of a tuple. IndexError: list index out of range

I created a db with sqlite3 in python, I then added a table with 5 parameters.我在 python 中用 sqlite3 创建了一个 db,然后我添加了一个带有 5 个参数的表。 I added an entry to the table filling all 5 parameters.我在表格中添加了一个条目,填充了所有 5 个参数。 I'm trying to select all entries with a specific parameter 'user'.我正在尝试选择具有特定参数“用户”的所有条目。

If I print the selected tuple without an index, it returns a tuple with 5 parameters as expected .如果我在没有索引的情况下打印选定的元组,它会按预期返回一个带有 5 个参数的元组。

If I print the tuple with an index of [0], it return a tuple with 5 parameters instead of the first parameter only.如果我打印索引为 [0] 的元组,它会返回一个带有 5 个参数的元组,而不是仅返回第一个参数。

If I print the entry with an index of higher than [0], for example [1], it returns IndexError: list index out of range.如果我打印索引高于 [0] 的条目,例如 [1],它会返回IndexError: list index out of range。

I would like to access all of the indexes, but I don't know how to do it other than how I tried.我想访问所有索引,但除了我尝试过的方法外,我不知道该怎么做。

Code below: (financedb is my other .py file that contains a function db_connect() connecting to the database. I included that function in the code below so that the code is easier to replicate.)下面的代码:(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()  

.fetchall returns a list of rows, so I would assume that you want check[0][0] ? .fetchall返回一个行列表,所以我假设你想要check[0][0] This may give you what you want:这可能会给你你想要的:

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])

I believe fetchall will return a list of rows, so check[0] represents the first row, of which the first element is the one you are looking for.我相信fetchall会返回一个行列表,所以check[0]代表第一行,其中第一个元素是您要查找的元素。 It may also return an empty list though, I would check if its length is positive before accessing the first value它也可能返回一个空列表,我会在访问第一个值之前检查它的长度是否为正

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM