Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate through cur.fetchall() in Python

I am working on database connectivity in Python 3.4. There are two columns in my database.

Below is the query which gives me all the data from two columns in shown format QUERY:

cur.execute(""" select * from filehash """)
data=cur.fetchall()
print(data)

OUTPUT:

[('F:\\test1.py', '12345abc'), ('F:\\test2.py', 'avcr123')]

To iterate through this output, my code is as below

cur.execute(""" select * from filehash """)
data=cur.fetchall()

i=0
j=1

for i,row in data:
    print(row[i])
    print(row[j])
    i=i+1

This gives me below error

print(row[i])
TypeError: string indices must be integers

Let me know how can we work on individual values of fetchall()

like image 361
npormambi Avatar asked Dec 25 '15 15:12

npormambi


2 Answers

It looks like you have two colunms in the table, so each row will contain two elements.

It is easiest to iterate through them this way:

for column1, column2 in data:

That is the same as:

for row in data:
    column1, column2 = row

You could also, as you tried:

for row in data:
    print row[0] # or row[i]
    print row[1] # or row[j]

But that failed because you overwrote i with the value of first column, in this line: for i, row in data:.

EDIT

BTW, in general, you will never need this pattern in Python:

i = 0
for ...:
    ...
    i += 1

Instead of that, it is common to do simply:

for item in container:
    # use item

# or, if you really need i:
for i, item in enumerate(container):
    # use i and item
like image 146
zvone Avatar answered Oct 02 '22 03:10

zvone


To iterate over and print rows from cursor.fetchall() you'll just want to do:

for row in data:
    print row

You should also be able to access indices of the row, such as row[0], row[1], iirc.

Of course, instead of printing the row, you can manipulate that row's data however you need. Imagine the cursor as a set of rows/records (that's pretty much all it is).

like image 44
Redbeard011010 Avatar answered Oct 02 '22 04:10

Redbeard011010