Files
tophux_scrape/product/update_database.py
2025-12-03 19:51:12 +08:00

77 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库更新脚本
用于更新现有的product_analysis表添加follows字段
"""
import sqlite3
import os
from loguru import logger
import sys
# 配置日志
logger.remove()
logger.add(sys.stderr, level="INFO", format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>")
def update_product_analysis_table(db_path):
"""更新product_analysis表添加follows字段"""
logger.info(f"开始更新数据库: {db_path}")
try:
# 连接数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 检查product_analysis表是否存在
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='product_analysis'")
table_exists = cursor.fetchone() is not None
if not table_exists:
logger.error("product_analysis表不存在无法更新")
conn.close()
return False
# 检查follows字段是否已经存在
cursor.execute("PRAGMA table_info(product_analysis)")
columns = [col[1] for col in cursor.fetchall()]
if 'follows' in columns:
logger.info("follows字段已经存在无需更新")
conn.close()
return True
# 添加follows字段
cursor.execute("ALTER TABLE product_analysis ADD COLUMN follows INTEGER")
conn.commit()
logger.success("成功为product_analysis表添加follows字段")
conn.close()
return True
except Exception as e:
logger.error(f"更新数据库失败: {e}")
if 'conn' in locals():
conn.close()
return False
def main():
"""主函数"""
# 获取默认数据库路径
default_db_path = os.path.join(os.path.dirname(__file__), "products.db")
logger.info("=== 数据库更新脚本开始执行 ===")
# 更新数据库
success = update_product_analysis_table(default_db_path)
if success:
logger.success("=== 数据库更新成功 ===")
sys.exit(0)
else:
logger.error("=== 数据库更新失败 ===")
sys.exit(1)
if __name__ == "__main__":
main()