query_buy_buyer_data.py 3.72 KB
#!/usr/bin/env python3
"""查询 buy_buyer 表的示例数据"""

import os
import pymysql
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from config.offline_config import DB_CONFIG

def query_sample_data():
    """查询示例数据"""
    try:
        # 连接数据库
        connection = pymysql.connect(
            host=DB_CONFIG['host'],
            port=int(DB_CONFIG['port']),
            user=DB_CONFIG['username'],
            password=DB_CONFIG['password'],
            database=DB_CONFIG['database'],
            charset='utf8mb4'
        )

        with connection.cursor() as cursor:
            # 查询指定字段的示例数据
            sql = """
            SELECT id, lang, customer_brand, countries, province, city, area, city_code
            FROM buy_buyer
            WHERE is_delete = 0
            LIMIT 20
            """
            cursor.execute(sql)
            result = cursor.fetchall()

            # 获取列名
            columns = [desc[0] for desc in cursor.description]

            print("=" * 140)
            print(f"{'ID':<15} {'语言':<10} {'客户品牌':<20} {'国家':<15} {'省份':<20} {'城市':<20} {'区域':<15} {'城市代码':<10}")
            print("=" * 140)

            for row in result:
                id_val = row[0] if row[0] is not None else ''
                lang = row[1] if row[1] is not None else ''
                brand = row[2] if row[2] is not None else ''
                countries = row[3] if row[3] is not None else ''
                province = row[4] if row[4] is not None else ''
                city = row[5] if row[5] is not None else ''
                area = row[6] if row[6] is not None else ''
                city_code = row[7] if row[7] is not None else ''

                # 截断过长的字符串
                brand = (brand[:18] + '..') if len(brand) > 20 else brand
                province = (province[:18] + '..') if len(province) > 20 else province
                city = (city[:18] + '..') if len(city) > 20 else city

                print(f"{id_val:<15} {lang:<10} {brand:<20} {countries:<15} {province:<20} {city:<20} {area:<15} {city_code:<10}")

            print("=" * 140)
            print(f"\n总计: {len(result)} 条记录")

            # 查询字段值分布统计
            print("\n" + "=" * 80)
            print("字段值分布统计:")
            print("=" * 80)

            stats_queries = [
                ("语言 (lang)", "SELECT lang, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY lang ORDER BY cnt DESC LIMIT 10"),
                ("国家 (countries)", "SELECT countries, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY countries ORDER BY cnt DESC LIMIT 10"),
                ("省份 (province)", "SELECT province, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY province ORDER BY cnt DESC LIMIT 10"),
                ("城市 (city)", "SELECT city, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY city ORDER BY cnt DESC LIMIT 10"),
                ("客户品牌 (customer_brand)", "SELECT customer_brand, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY customer_brand ORDER BY cnt DESC LIMIT 10"),
            ]

            for title, query in stats_queries:
                print(f"\n【{title}】")
                cursor.execute(query)
                stats = cursor.fetchall()
                for row in stats:
                    value = row[0] if row[0] is not None else '(NULL)'
                    count = row[1]
                    print(f"  {value:<30} {count:>10} 条")

    except Exception as e:
        print(f"查询失败: {e}")
    finally:
        if 'connection' in locals():
            connection.close()

if __name__ == "__main__":
    query_sample_data()