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



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

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

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

如果我打印索引高于 [0] 的条目,例如 [1],它会返回IndexError:列出超出范围的索引。

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

下面的代码:(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返回行列表,所以我假设你想要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])

我相信fetchall会返回一个行列表,所以check[0]代表第一行,其中第一个元素是您要查找的元素。它也可能返回一个空列表,我会在访问第一个值之前检查它的长度是否为正

最新更新