Reputation: 331
I created a db with sqlite3 in python, I then added a table with 5 parameters. I added an entry to the table filling all 5 parameters. 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.
If I print the tuple with an index of [0], it return a tuple with 5 parameters instead of the first parameter only.
If I print the entry with an index of higher than [0], for example [1], it returns 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.)
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()
Upvotes: 0
Views: 570
Reputation: 575
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. It may also return an empty list though, I would check if its length is positive before accessing the first value
Upvotes: 1
Reputation: 434
.fetchall
returns a list of rows, so I would assume that you want 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])
Upvotes: 1