# 看表 · 课堂演示件
#
# 作用：把 items.db 里两张表的内容原样打印出来。
#       没有安装 DB Browser 时，用这个脚本也能看见数据库里真实的样子。
# 用法：与 items.db 放在同一位置，直接运行。

import sqlite3
from pathlib import Path

DB = Path(__file__).with_name('items.db')

if not DB.exists():
    print('没有找到 items.db，请先运行 第13章演示_建库.py。')
    input('按回车键结束')
    raise SystemExit

conn = sqlite3.connect(DB)

# ① 先问数据库自己有哪几张表
tables = conn.execute(
    "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
).fetchall()

for (table,) in tables:
    print()
    print('===== 表：' + table + ' =====')

    # ② 再问这张表有哪些字段
    columns = [row[1] for row in conn.execute('PRAGMA table_info(' + table + ')')]
    print(' | '.join(columns))
    print('-' * 60)

    # ③ 把整张表打出来。空值显示成「（空）」，便于看清哪些字段还没填
    rows = conn.execute('SELECT * FROM ' + table).fetchall()
    for row in rows:
        print(' | '.join('（空）' if v is None else str(v) for v in row))
    print('共', len(rows), '行')

conn.close()
input('按回车键结束')
