0

I have this function, which I am obtaining all the names from employees, the problem is, i only get the last record, not all of them I want all these names: Maria, John, Sam but it returns only Sam. I am using a class because I need to follow the code's structure the last programmer did.

My class:

class name_data:
    def __init__(self):
       self.name           = 'null'
def getNames (conn):
    cursor = conn.cursor()
    query = """SELECT NAME FROM PERSON"""
    cursor.execute(query)
    row =  cursor.fetchone() 
    while row: 
        sent_person      = name_data()
        sent_person.name = row[0]
        row = cursor.fetchone()
        
    return sent_person
Mikasa
  • 47
  • 3

1 Answers1

1

In your code you are just returning the name of the person who was recorded in the variable for that loop. So you only will get the last name in the loops.

Create a variable to store the names and return the variable like this. You could use a list.

I am guessing you want the sent_person variable in every loop


def getNames (conn):
    names = [] #list variable
    cursor = conn.cursor()
    query = """SELECT NAME FROM PERSON"""
    cursor.execute(query)
    row =  cursor.fetchone() 
    while row: 
        sent_person      = name_data()
        sent_person.name = row[0]
        row = cursor.fetchone()
        names.append(sent_person) #append name in every loop
    return names #return the list
newbie01
  • 136
  • 4