【问题标题】:How to print a table in sqlite3 along with column names in python using a loop and how exactly to get the column names?如何使用循环打印 sqlite3 中的表以及 python 中的列名以及如何准确获取列名?
【发布时间】:2020-04-22 15:47:11
【问题描述】:

我有一个包含 7 列的学生数据库。当我尝试直接打印输出时,输出以 [(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])

其中表名是列名列表

【问题讨论】:

    标签: python python-3.x sqlite python-sql


    【解决方案1】:
    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。

    【讨论】:

    • 我得到了这个错误 ``` names = [description[0] for description in c.description] TypeError: 'NoneType' object is not iterable ```
    • 您在代码中使用了 c.description。复制正确的代码。
    猜你喜欢
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2013-08-24
    • 2018-05-17
    相关资源
    最近更新 更多