Reputation: 11
I am using Python3.6.
Database table example:
column1 . .column2 . .column3
....10 ...........20..............30
....100 ....... 200.............300
Code:
# 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
How do I add the column names manually to this loop so that it is included in the output?
I am new to stackoverflow so this post will need improvements in formatting, content, etc., so I welcome any feedback.
Thank you!
Upvotes: 1
Views: 475
Reputation: 1155
If you want the headers to be available with each row of data, make a DictCursor
. In my knowledge, most popular MySQL, Oracle, Postgres libs support it.
Then you can do this:
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
Reference: generator
Upvotes: 0
Reputation: 164693
You can use cursor.description
to extract headers and then iterate headers and data via itertools.chain
:
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
If formatting as a table with consistent spacing is important, see Printing Lists as Tabular Data.
Upvotes: 1
Reputation: 565
if you're adding column names manually just do print the column names outside of the for loop.
print("col1\tcol2\tcol3")
for row in rows:
print(row)
Upvotes: 0