简体   繁体   中英

How to print a table in sqlite3 along with column names in python using a loop and how exactly to get the column names?

I have a student database with the 7 columns in it. When I try printing the output directly the output is printed in [(r1, r2,r3,r4...),(),(),....] format without the column names. So I decided to loop through the values and wrote this:

c.execute("select * from student")
rows = c.fetchall()
for row in rows:
    print("s_id",row[0])
    print("s_name,row[1])
    .
    .until the table ends

Is there a way by which i can get my column names directly so that i can write it using one print statement inside the above loop?????? for eg: something like this

c.execute("select * from student")
rows = c.fetchall()
for row in rows:
    print("table_name[i]",row[i])

where table name is the list of column names

Adding to the above right answer because I dont have reputation to just comment, in case you're like me and learning

The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

The code I was looking to do was to just print one column from a fetch all. I am not sure which is faster, doing separate DB calls, or just one db call and dealing with the data that way. (bit off topic)

Thank you MSS!

    def openDB(self, *args):
    repeat = 0
    con = sqlite3.connect("ModerateControls.db")
    cursorObj = con.cursor()
    cursorObj.execute('SELECT * FROM "Access Control"')
    names = [description[0] for description in cursorObj.description]
    rows = cursorObj.fetchall()
    for row in rows:
        for name,val in zip(names,row):
            if name=='ControlID':
                print(val)
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
cursor = connection.execute('select * from student')
# Get the name of columns
names = [description[0] for description in cursor.description]
rows = cursor.fetchall()
for row in rows:
    for name, val in zip(names,row):
        print( name, val)

use cursor.description in a list comprehension like the one above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM