[英]How to print a table in sqlite3 along with column names in python using a loop and how exactly to get the column names?
我有一个包含 7 列的学生数据库。 当我尝试直接打印 output 时,output 以 [(r1, r2,r3,r4...),(),(),....] 格式打印,没有列名。 所以我决定遍历这些值并写下这个:
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
有没有一种方法可以直接获取我的列名,以便我可以在上述循环中使用一个打印语句来编写它?????? 例如:像这样的东西
c.execute("select * from student")
rows = c.fetchall()
for row in rows:
print("table_name[i]",row[i])
其中表名是列名列表
添加到上面的正确答案,因为我没有评论的声誉,以防你像我一样学习
zip() function 接受迭代(可以是零或更多),将它们聚合到一个元组中,然后返回它。
我想做的代码是从 fetch all 中打印一列。 我不确定哪个更快,进行单独的数据库调用,或者只是一个数据库调用并以这种方式处理数据。 (有点跑题了)
谢谢你!
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)
在上面的列表理解中使用 cursor.description 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.