You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python循环遍历SQLite安卓通话日志表并显示记录与列标题

Solution

Here's how you can tweak your code to display column headers alongside each table's records, making the output way easier to read:

import sqlite3

# Set up your database connection and cursor (adjust the DB path as needed)
conn = sqlite3.connect('your_call_logs.db')
cursor = conn.cursor()

# Fetch all table names from sqlite_master (your existing logic)
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()

for table in tables:
    table_name = table[0]
    print(f"\n--- Table: {table_name} ---")  # Clear separator for each table
    
    # Run the SELECT query for the current table
    cursor.execute(f"SELECT * FROM {table_name}")
    rows = cursor.fetchall()
    
    # Extract column headers from the cursor's description
    column_headers = [col[0] for col in cursor.description]
    
    # Print headers first (tab-separated for readability)
    print("\t".join(column_headers))
    
    # Print each row, matching the header order
    for row in rows:
        # Convert all values to strings to avoid type errors when joining
        print("\t".join(str(item) for item in row))

# Don't forget to close the connection when done
conn.close()

Breakdown of the key changes:

  • Table Separation: Added a clear heading for each table so you can easily tell where one table's data ends and another begins.
  • Header Extraction: The cursor.description attribute holds metadata about your query results—we grab the first element of each tuple here, which is the column name.
  • Readable Formatting: Using tabs (\t) to separate values aligns headers with their corresponding rows, making the output far more organized than just printing raw tuples.
  • Type Safety: Converting each row item to a string ensures numbers, NULL values, and other non-string data types print without errors.

Bonus for cleaner output:

If you want even nicer, aligned columns, install the tabulate library (pip install tabulate) and replace the header/row printing section with this:

from tabulate import tabulate

# After fetching rows and column_headers:
print(tabulate(rows, headers=column_headers, tablefmt="simple_grid"))

This will add borders and auto-align all columns for a spreadsheet-like look.

内容的提问来源于stack exchange,提问作者delaros1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:18:56