This commit is contained in:
2025-09-23 20:13:58 +08:00
parent 5c8d07e5d7
commit ee2c28852d
18 changed files with 67 additions and 1498 deletions
+21 -79
View File
@@ -1,85 +1,27 @@
# -*- coding: utf-8 -*-
"""
检查数据库表的实际结构
"""
import sqlite3
import logging
# 配置日志
handlers = [logging.FileHandler('table_structure.log'), logging.StreamHandler()]
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=handlers
)
logger = logging.getLogger(__name__)
# 数据库文件路径
db_path = 'car_info.db'
def check_table_structure(table_name):
"""
检查指定表的结构
"""
logger.info(f"开始检查表 {table_name} 的结构")
# 连接到数据库
try:
conn = sqlite3.connect('car_info.db')
cursor = conn.cursor()
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 检查表是否存在
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
table_exists = cursor.fetchone() is not None
if not table_exists:
logger.error(f"{table_name} 不存在")
return
# 获取表的字段信息
cursor.execute(f"PRAGMA table_info({table_name})")
columns = cursor.fetchall()
logger.info(f"{table_name} 的字段信息:")
for column in columns:
logger.info(f"字段ID: {column[0]}, 字段名: {column[1]}, 数据类型: {column[2]}, 非空约束: {column[3]}, 默认值: {column[4]}, 主键: {column[5]}")
# 获取表中的记录数量
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
count = cursor.fetchone()[0]
logger.info(f"{table_name} 中的记录数量: {count}")
# 如果有记录,显示前5条记录的内容
if count > 0:
cursor.execute(f"SELECT * FROM {table_name} LIMIT 5")
rows = cursor.fetchall()
logger.info(f"{table_name} 的前5条记录:")
for row in rows:
logger.info(f"记录: {row}")
# 关闭数据库连接
conn.close()
except sqlite3.Error as e:
logger.error(f"数据库操作失败: {str(e)}")
except Exception as e:
logger.error(f"程序执行出错: {str(e)}")
def main():
"""
主函数
"""
logger.info("开始检查数据库表结构")
# 获取car_owners表的结构
cursor.execute('PRAGMA table_info(car_owners)')
rows = cursor.fetchall()
# 检查query_history表的结构
check_table_structure('query_history')
print('car_owners表结构:')
for row in rows:
print(row)
# 检查car_owners表的结构
check_table_structure('car_owners')
# 检查query_history表的结构,了解两个表的关系
print('\nquery_history表结构:')
cursor.execute('PRAGMA table_info(query_history)')
rows = cursor.fetchall()
for row in rows:
print(row)
logger.info("数据库表结构检查完成")
if __name__ == "__main__":
main()
except Exception as e:
print(f'查询表结构时出错: {e}')
finally:
if conn:
conn.close()