我在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]
代表第一行,其中第一元素是您要查找的元素。它也可能返回一个空列表,在访问第一个值之前,我会检查其长度是否为正。