+-
如何在Python中迭代cur.fetchall()
我正在使用 Python 3.4中的数据库连接.
我的数据库中有两列.

下面是查询,它以所示格式显示来自两列的所有数据
查询:

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

OUTPUT:

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

要遍历此输出,我的代码如下所示

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

这给了我以下错误

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

让我知道我们如何处理fetchall()的个别值

最佳答案
看起来表中有两个colunms,因此每行包含两个元素.

以这种方式迭代它们是最容易的:

for column1, column2 in data:

这与:

for row in data:
    column1, column2 = row

您也可以尝试:

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

但是那次失败了,因为你用第一列的值覆盖了i,在这一行中:对于i,在数据中输入:

编辑

顺便说一下,在Python中你永远不需要这种模式:

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

而不是那样,通常做的很简单:

for item in container:
    # use item

# or, if you really need i:
for i, item in enumerate(container):
    # use i and item
点击查看更多相关文章

转载注明原文:如何在Python中迭代cur.fetchall() - 乐贴网