_init_brand_config.py 3.16 KB
# -*- coding: utf-8 -*-
"""初始化"豪华品牌配置表"到数据库。
新建 config_brand_category 表(brand / category),从 xlsx 灌入,幂等。
"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
import pymysql
import openpyxl

XLSX = 'D:/workspace_daily/日常数据处理需求/运营数据处理/配置表/豪华品牌配置表.xlsx'
DB = {
    'host': '192.168.3.227', 'port': 3306,
    'user': 'os_user', 'password': 'os#123',
    'database': 'data_report', 'charset': 'utf8mb4',
}


def read_rows():
    wb = openpyxl.load_workbook(XLSX, data_only=True, read_only=True)
    ws = wb['Sheet1']
    rows = []
    header_skipped = False
    for r in ws.iter_rows(values_only=True):
        if not header_skipped:
            header_skipped = True
            continue  # 跳过表头「品牌/品牌区分」
        brand = (r[0] or '').strip() if r and len(r) > 0 else ''
        cat = (r[1] or '').strip() if r and len(r) > 1 else ''
        if not brand:
            continue
        rows.append((brand, cat or '豪华'))
    return rows


def main():
    rows = read_rows()
    print(f'从 xlsx 读取到 {len(rows)} 行品牌配置')

    conn = pymysql.connect(**DB)
    try:
        with conn.cursor() as cur:
            # 1) 建表(幂等)
            cur.execute('''
                CREATE TABLE IF NOT EXISTS config_brand_category (
                    id BIGINT NOT NULL AUTO_INCREMENT,
                    brand VARCHAR(200) NOT NULL COMMENT '品牌',
                    category VARCHAR(50) NOT NULL DEFAULT '' COMMENT '品牌区分(如 豪华/非豪华)',
                    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    PRIMARY KEY (id),
                    UNIQUE KEY uq_brand (brand(191))
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表'
            ''')
            print('[OK] 表 config_brand_category 就绪')

            # 2) 灌入(幂等:品牌重复则更新 category)
            inserted = 0
            updated = 0
            for brand, cat in rows:
                cur.execute(
                    'SELECT id FROM config_brand_category WHERE brand=%s', (brand,))
                if cur.fetchone():
                    cur.execute(
                        'UPDATE config_brand_category SET category=%s, update_time=NOW() WHERE brand=%s',
                        (cat, brand))
                    updated += 1
                else:
                    cur.execute(
                        'INSERT INTO config_brand_category (brand, category) VALUES (%s, %s)',
                        (brand, cat))
                    inserted += 1
            conn.commit()
            print(f'[OK] 插入 {inserted} 行,更新 {updated} 行')

            # 3) 校验
            cur.execute('SELECT COUNT(*) FROM config_brand_category')
            print('库内总行数:', cur.fetchone()[0])
            cur.execute('SELECT brand, category FROM config_brand_category ORDER BY id')
            for r in cur.fetchall():
                print('  ', r)
    finally:
        conn.close()


if __name__ == '__main__':
    main()