【问题标题】:using python, how do i loop using a for loop to display the records from each table showing all the columns and the respective column headers使用python,我如何循环使用for循环来显示每个表中的记录,显示所有列和相应的列标题
【发布时间】:2018-04-20 08:08:56
【问题描述】:

我在 android 中有一个用于调用日志的 sqlite 数据库虚拟数据,使用从 sqlite master 中选择不同表的查询,我如何使用 python for loop 循环显示每个表中的记录,显示所有列和相应的列标题。这是python代码中的一段:

for table in tables:
    cursor.execute("SELECT * FROM %s" % table[0])
    rows = cursor.fetchall()

    for row in rows:
        print row # prints records in the all the tables without column headers

【问题讨论】:

  • 这段代码应该可以工作。是吗?

标签: python sqlite


【解决方案1】:

默认情况下,sqlite 不支持 information_schema。您需要单独收集表模式。
我们可以使用编译指示,

cursor.execute('PRAGMA TABLE_INFO(tablename)

或者我们可以使用 cursor.description,

column[0] for column in c.description

它将列名存储为列表。
你可以修改你的代码,像这样。

for table in tables:
column = []
cursor.execute("SELECT * FROM %s" % table[0])
rows = cursor.fetchall()
column = column[0] for column in cursor.description
i=0
for row in rows:
    if i == 0:
        print(column)
    else:
        print row # prints records in the all the tables without column headers
    i = i+1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 2023-03-12
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多