python - 无法访问元组的索引。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()
解决方案
.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])
推荐阅读
- javascript - 根据不透明度值将 6 位十六进制颜色转换为 6 位十六进制颜色
- java - Joda Time toDate() 错误结果
- android - 使用 PackageInstaller 在 Android 中进行并行安装
- c++ - 我需要帮助修复我的 C++ 程序 - 没有错误,没有打印我想要的内容
- php - 如何在各种 div 中显示我的 preg_match 结果,以便它们可以在正确的标题下有多个结果?
- python - 为什么 pandas .last('1W') 不显示最后 7 天?
- python - 如何在用户给出的输入中的两个字符之间放置一个空格?我的错误在哪里??(我是初学者
- spring-mvc - 如何在 htmlunit 中上传 MultipartFile?
- android - 通过 okHttp 套接字发送数据
- python-3.x - 将一行翻译成几行