Link to home
Start Free TrialLog in
Avatar of Dolamite Jenkins
Dolamite JenkinsFlag for United States of America

asked on

return a list

In trying to return a list from my database and the print then rows[1],rows[2],rows[3] etc and i cant get my list to work below but when I try ab= [str(rows[2])for rows in cur.fetchall()] iot works but I cant return more that that one so I has to do it ove and ove again but cant getit to print correctly... what am I doing wrong in the first part andwhy is reutning a list in using a db like sqlite diffrerent from using a .txt ?

rows=[]
	    con = lite.connect('specialeventms.sqlite')
		
	    cur = con.cursor()
		
	     
	    cur.execute("select * from  ptrecords ")			    
	    cur.fetchall()
	    for rows in row:
	   
	    
		self.ic = rows[0]
		
		self.ln = rows[1]
		self.fn = rows[2]
		self.age = (str(rows[3]))
		self.gen = rows[4]
		self.add = rows[5]
		self.city= rows[6]
		self.state = rows[7]
		
		self.ail = rows[9]
		self.treat = rows[10]
	    return rows
		print row[1], row[2],row[3]

Open in new window


 a = [str(rows[1])for rows in cur.fetchall()]
ab= [str(rows[2])for rows in cur.fetchall()]
abc = [str(rows[9])for rows in cur.fetchall()]
abcd= [str(rows[10])for rows in cur.fetchall()]

print a,ab,abc, abcd

Open in new window

Avatar of pepr
pepr

When looping through the records, you get the row one by one.  If you want lists that reflect the columns in one loop through the table, you have to build all the lists in the same time.   Or you have to do that inside the loop and return the resulting lists at the end of the function, or you can use the yield command instead of the return to get one-by-one record from inside the generator function and process the record outside of that function.

From your code it looks that there is some confusion between row/rows -- actually the names should be switched.  The print returns the whole records (but it is never executed) while the "return rows" returns one row.  The cur.fetchall() should probably be assigned to rows or better be the part of the for loop.
I guess from the code

                self.ic = rows[0]
		
		self.ln = rows[1]
		self.fn = rows[2]
		self.age = (str(rows[3]))
		self.gen = rows[4]
		self.add = rows[5]
		self.city= rows[6]
		self.state = rows[7]
		
		self.ail = rows[9]
		self.treat = rows[10]

Open in new window


that you may want to extract the data from one record and form an object that captures meaning of the data.  You may then want to build the list of those objects.  You should write more about your intention.  Definitely, it will not work when making it the part of the self as you would modify always the same object.
ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dolamite Jenkins

ASKER

thanks