owwix
owwix

Reputation: 73

how to populate a list with sql queries

I have an empty list contacts = []. I also have a sqlite3 database, with each row containing first_name, last_name, email, phone_number, address for a person. I want to populate my empty contacts list with a list [first_name, last_name, email, phone_number, address] for each individual/row in the database.

The way I am thinking to do it is doing

tempvar = cursor.fetchall()
rowcount = len(tempvar)

to get the number of rows in the database, to be used in a for loop as such:

for n in range(0, rowcount):
    contacts.append([a,
                     b,
                     c,
                     d,
                     e])

but I want a b c d and e to be queries for first_name, last_name, email, phone_number, and address of the nth person. Can someone help me fill in the blank? Hopefully I am making sense!

Upvotes: 1

Views: 695

Answers (1)

Gustavo Araújo
Gustavo Araújo

Reputation: 90

I made a database in sqlite3 with the columns, added 2 contacts and made the following code below:

import sqlite3

conn = sqlite3.connect('db/teste.db', check_same_thread=False)
c = conn.cursor()
contacts = c.execute("SELECT * FROM contacts").fetchall()

for x in range(len(contacts)):
    print(contacts[x])

The result of the code below:

('Gustavo', 'Araujo', '[email protected]', '556818293893', 'QELC04 BL B9')
('Fernando', 'Soares', '[email protected]', '559849892830', 'ASA SUL BSB')

Upvotes: 1

Related Questions