85 lines
2.4 KiB
Python
85 lines
2.4 KiB
Python
# -*- 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(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("开始检查数据库表结构")
|
|
|
|
# 检查query_history表的结构
|
|
check_table_structure('query_history')
|
|
|
|
# 检查car_owners表的结构
|
|
check_table_structure('car_owners')
|
|
|
|
logger.info("数据库表结构检查完成")
|
|
|
|
if __name__ == "__main__":
|
|
main() |