xxx
This commit is contained in:
103
db_viewer.py
Normal file
103
db_viewer.py
Normal file
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import sqlite3
|
||||
import sys
|
||||
import os
|
||||
|
||||
def print_separator(char='-', length=80):
|
||||
"""打印分隔线"""
|
||||
print(char * length)
|
||||
|
||||
def show_database_info(db_path):
|
||||
"""显示数据库信息"""
|
||||
if not os.path.exists(db_path):
|
||||
print(f"错误:数据库文件 '{db_path}' 不存在")
|
||||
return
|
||||
|
||||
try:
|
||||
# 连接到数据库
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 获取所有表名
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
|
||||
tables = cursor.fetchall()
|
||||
|
||||
if not tables:
|
||||
print("数据库中没有表")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
print(f"在数据库 '{db_path}' 中找到 {len(tables)} 个表:")
|
||||
print_separator()
|
||||
|
||||
# 显示每个表的结构和数据
|
||||
for table in tables:
|
||||
table_name = table[0]
|
||||
print(f"\n表名: {table_name}")
|
||||
print_separator()
|
||||
|
||||
# 获取表结构
|
||||
cursor.execute(f"PRAGMA table_info({table_name});")
|
||||
columns = cursor.fetchall()
|
||||
|
||||
# 打印列名
|
||||
col_names = [col[1] for col in columns]
|
||||
col_types = [col[2] for col in columns]
|
||||
print("表结构:")
|
||||
for i, (name, type_) in enumerate(zip(col_names, col_types)):
|
||||
print(f" {i+1}. {name} ({type_})")
|
||||
|
||||
# 获取记录数
|
||||
cursor.execute(f"SELECT COUNT(*) FROM {table_name};")
|
||||
count = cursor.fetchone()[0]
|
||||
print(f"\n记录数: {count}")
|
||||
|
||||
# 获取表数据 (最多显示10条)
|
||||
if count > 0:
|
||||
cursor.execute(f"SELECT * FROM {table_name} LIMIT 10;")
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print("\n数据预览 (最多10条):")
|
||||
print_separator()
|
||||
|
||||
# 打印列名
|
||||
for col in col_names:
|
||||
print(f"{col:15}", end="")
|
||||
print("\n" + "-" * (15 * len(col_names)))
|
||||
|
||||
# 打印数据
|
||||
for row in rows:
|
||||
for item in row:
|
||||
# 对值进行截断,防止过长的数据破坏格式
|
||||
item_str = str(item)
|
||||
if len(item_str) > 13:
|
||||
item_str = item_str[:10] + "..."
|
||||
print(f"{item_str:15}", end="")
|
||||
print()
|
||||
|
||||
if count > 10:
|
||||
print(f"...(还有 {count-10} 条记录)")
|
||||
|
||||
print_separator("=")
|
||||
|
||||
conn.close()
|
||||
print("\n查询完成!")
|
||||
|
||||
except sqlite3.Error as e:
|
||||
print(f"SQLite 错误: {e}")
|
||||
except Exception as e:
|
||||
print(f"发生错误: {e}")
|
||||
|
||||
def show_usage():
|
||||
"""显示使用帮助"""
|
||||
print(f"使用方法: python {os.path.basename(__file__)} <数据库文件路径>")
|
||||
print("示例: python db_viewer.py C:\\path\\to\\your\\database.db")
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
show_usage()
|
||||
else:
|
||||
db_path = sys.argv[1]
|
||||
show_database_info(db_path)
|
||||
Reference in New Issue
Block a user