如何为循环中的每一行数据添加列标题?

2024-05-14 17:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是Python3.6

数据库表示例:

column1 . .column2  . .column3

....10    ...........20..............30

....100  .......     200.............300

代码:

# extracts all data for the rows without the column names
rows=cursor.fetchall()

for row in rows:
    print(row)

  10   20   30  
  100  200  300

如何将列名手动添加到此循环中,以便将其包含在输出中

我是stackoverflow的新手,所以这篇文章在格式、内容等方面需要改进,所以我欢迎任何反馈

谢谢你


Tags: the代码数据库fordatanamescolumnall
3条回答

可以使用^{}提取头,然后通过^{}迭代头和数据:

from itertools import chain
from operator import itemgetter

headers = [list(map(itemgetter(0), cursor.description))]
rows = cursor.fetchall()

for row in chain(headers, rows):
    print(*row)

column1 column2 column3
10 20 30
100 200 300

如果格式化为具有一致间距的表格很重要,请参见Printing Lists as Tabular Data

如果希望每行数据都有可用的标题,请使用DictCursor。据我所知,最流行的MySQL、Oracle、Postgres libs都支持它

然后你可以这样做:

conn = MySQLdb.connect(host,port,user,passwd,db)
cursor = van.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM table;")

# Avoid doing fetchall(). If your query resukt is big enough, it can even make your program run out of available memory of the system.
#rows=cursor.fetchall()

#Alternatively, iterate over the cursor itself, which is a generator

for row in cursor:
    print row

引用:generator

如果手动添加列名,只需在for循环外打印列名

print("col1\tcol2\tcol3")
for row in rows:
   print(row)

相关问题 更多 >

    热门问题