##120.55.6.12:3306 root Chen@123456
import  pandas as pd
import  pymysql
df_clean = pd.read_csv("./clean.csv")
db_config = {
    'host': '120.55.6.12',
    'port': 3306,
    'user': 'root',
    'password': 'Chen@123456',
    'charset': 'utf8mb4',
    'database': 'ecm_analysis'
}

df_mysql = df_clean.copy()
conn = pymysql.connect(**db_config)

# 插入订单数据
table_name = 'orders'
try:
    with conn.cursor() as cursor:
        cursor.execute(f"delete from {table_name}")
        for index, row in df_mysql.iterrows():
            sql = f'insert into {table_name} ({", ".join(row.index)}) values({", ".join(["%s"] * len(row))})'
            print("sql->", sql)
            print(tuple(row))
            cursor.execute(sql, tuple(row))
        conn.commit()
except Exception as e:
    print("数据操作错误", e)
    conn.rollback()
finally:
    conn.close()
# 用户行为汇总数据
user_behavior_df = df_clean.groupby('user_id').agg({
    'order_id': 'count',
    'total_amount': 'sum',
    'category': lambda x: x.mode()[0],
    'order_date': 'max'
}).reset_index()

user_behavior_df['avg_order_value'] = user_behavior_df['total_amount'] / user_behavior_df['order_id']
user_behavior_df.columns = ['user_id', 'total_orders', 'total_spent', 'favorite_category', 'last_order_date',
                            'avg_order_value']

conn = pymysql.connect(**db_config)
table_name = 'user_behavior'
try:
    with conn.cursor() as cursor:
        cursor.execute(f"delete from {table_name}")
        for index, row in user_behavior_df.iterrows():
            sql = f'insert into {table_name} ({", ".join(row.index)}) values({", ".join(["%s"] * len(row))})'
            print("sql->", sql)
            print(tuple(row))
            cursor.execute(sql, tuple(row))
        conn.commit()
except Exception as e:
    print("数据操作错误", e)
    conn.rollback()
finally:
    conn.close()

def execute_sql_query(query) :
    conn = pymysql.connect(**db_config)
    try :
        with conn.cursor() as cursor :
            cursor.execute(query)
            result = cursor.fetchall()
            columns = [desc[0] for desc in cursor.description]
            return pd.DataFrame(result,columns=columns)
    except Exception as e :
        print(e)
        return None
    finally:
        conn.close()