sync_data.py 2.54 KB
import pymysql
import sqlite3
import os
import schedule
import time
import datetime

# 数据库配置
MYSQL_CONFIG = {
    'host': '192.168.3.222',
    'port': 3308,
    'user': 'os_user',
    'password': 'os#123',
    'database': 'scrm_account',
    'charset': 'utf8mb4'
}

# 获取当前脚本所在目录,确保数据库文件在同级目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SQLITE_DB_PATH = os.path.join(BASE_DIR, 'merchants_fts.db')

def preprocess_text(text):
    """在每个字符间添加空格,支持 FTS5 间隙匹配"""
    if not text: return ""
    return " ".join(list(str(text).replace(" ", "")))

def sync_task():
    """执行同步任务的主函数"""
    print(f"[{datetime.datetime.now()}] 开始执行同步任务...")
    
    # 建立 SQLite 连接
    # 如果表不存在则创建,如果存在则清空重写(全量同步)
    sqlite_conn = sqlite3.connect(SQLITE_DB_PATH)
    sqlite_cursor = sqlite_conn.cursor()
    
    try:
        # 1. 初始化 SQLite 表结构
        sqlite_cursor.execute("DROP TABLE IF EXISTS merchants;")
        sqlite_cursor.execute("CREATE VIRTUAL TABLE merchants USING fts5(merchantNo UNINDEXED, name);")

        # 2. 从 MySQL 读取数据
        mysql_conn = pymysql.connect(**MYSQL_CONFIG)
        try:
            with mysql_conn.cursor() as mysql_cursor:
                sql = "SELECT merchantNo, merchant_name FROM platform_merchant"
                mysql_cursor.execute(sql)
                rows = mysql_cursor.fetchall()
                print(f"从 MySQL 读取到 {len(rows)} 条记录。")

                # 3. 批量同步到 SQLite
                batch_data = [(m_no, preprocess_text(m_name)) for m_no, m_name in rows]
                sqlite_cursor.executemany("INSERT INTO merchants (merchantNo, name) VALUES (?, ?);", batch_data)
                sqlite_conn.commit()
                print(f"[{datetime.datetime.now()}] 同步成功!共写入 {len(rows)} 条数据。")
        finally:
            mysql_conn.close()

    except Exception as e:
        print(f"[{datetime.datetime.now()}] 同步失败: {e}")
    finally:
        sqlite_conn.close()

def run_scheduler():
    """设置并运行定时器"""
    # 1. 启动时立即运行一次
    sync_task()
    
    # 2. 每 12 小时运行一次
    schedule.every(12).hours.do(sync_task)
    
    print("定时任务已启动,每 12 小时同步一次。按 Ctrl+C 停止。")
    while True:
        schedule.run_pending()
        time.sleep(60) # 每分钟检查一次任务状态

if __name__ == "__main__":
    run_scheduler()