"""彻底删除老的 news_posts / news_categories 表。 运行前已手动备份 cms.db -> cms.db.backup_before_news_cleanup_20260429 """ from sqlalchemy import create_engine, text engine = create_engine('sqlite:///cms.db') with engine.connect() as conn: # 先看看在不在 tables_before = [r[0] for r in conn.execute(text( "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('news_posts','news_categories')" )).fetchall()] print(f"清理前存在的老表: {tables_before}") # 记录数据量(仅记录,不影响清理) for t in tables_before: cnt = conn.execute(text(f"SELECT COUNT(*) FROM {t}")).scalar() print(f" {t}: {cnt} 行") # DROP 顺序:先 news_posts(含 FK 指向 news_categories),再 news_categories if 'news_posts' in tables_before: conn.execute(text("DROP TABLE news_posts")) print("已 DROP TABLE news_posts") if 'news_categories' in tables_before: conn.execute(text("DROP TABLE news_categories")) print("已 DROP TABLE news_categories") conn.commit() tables_after = [r[0] for r in conn.execute(text( "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('news_posts','news_categories')" )).fetchall()] print(f"\n清理后存在的老表: {tables_after}(应为空)")