How to Iterate through cur.fetchall() in Python

前端 未结 5 923
刺人心
刺人心 2021-01-02 18:18

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 f

5条回答
  •  耶瑟儿~
    2021-01-02 19:03

    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
    

提交回复
热议问题