import logging import asyncio import uuid from aiomysql import create_pool from datetime import datetime # MYSQL配置信息 MYSQL_HOST = "10.10.14.203" MYSQL_PORT = 3306 MYSQL_USER = "root" MYSQL_PASSWORD = "Password123@mysql" MYSQL_DB_NAME = "xiaozhi_esp32_server" # 配置日志 logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") logger = logging.getLogger(__name__) # MySQL 配置 MYSQL_CONFIG = { "host": MYSQL_HOST, "port": MYSQL_PORT, "user": MYSQL_USER, "password": MYSQL_PASSWORD, "db": MYSQL_DB_NAME, "minsize": 1, "maxsize": 20, "autocommit": True, "charset": "utf8mb4", } async def init_mysql_pool(): """初始化 MySQL 连接池""" try: pool = await create_pool(**MYSQL_CONFIG) logger.info("MySQL连接池创建成功") return pool except Exception as e: logger.error(f"创建MySQL连接池失败: {str(e)}") raise async def truncate_chat_log(pool): """清空聊天历史表""" try: async with pool.acquire() as conn: await conn.ping() async with conn.cursor() as cur: await cur.execute("TRUNCATE TABLE t_chat_history") logger.info("表 t_chat_history 已清空") except Exception as e: logger.error(f"清空表失败: {str(e)}") raise async def insert_chat_log(pool, chat_text, chat_wav, ai_text, person_id, person_name): """插入聊天记录""" try: async with pool.acquire() as conn: await conn.ping() async with conn.cursor() as cur: sql = """ INSERT INTO t_chat_history (chat_text, chat_wav, ai_text, person_id, person_name) VALUES (%s, %s, %s, %s, %s) """ await cur.execute(sql, (chat_text, chat_wav, ai_text, person_id, person_name)) logger.info(f"成功插入聊天记录: {person_name}") return cur.lastrowid except Exception as e: logger.error(f"插入聊天记录失败: {str(e)}") raise async def update_chat_log(pool, chat_id, chat_text=None, chat_wav=None, ai_text=None, person_name=None): """更新聊天记录""" try: async with pool.acquire() as conn: await conn.ping() async with conn.cursor() as cur: # 构建更新语句 updates = [] params = [] if chat_text is not None: updates.append("chat_text = %s") params.append(chat_text) if chat_wav is not None: updates.append("chat_wav = %s") params.append(chat_wav) if ai_text is not None: updates.append("ai_text = %s") params.append(ai_text) if person_name is not None: updates.append("person_name = %s") params.append(person_name) if not updates: logger.warning("没有提供要更新的字段") return params.append(chat_id) sql = f"UPDATE t_chat_history SET {', '.join(updates)} WHERE id = %s" await cur.execute(sql, params) logger.info(f"成功更新聊天记录 ID: {chat_id}") except Exception as e: logger.error(f"更新聊天记录失败: {str(e)}") raise async def delete_chat_log(pool, chat_id): """删除聊天记录""" try: async with pool.acquire() as conn: await conn.ping() async with conn.cursor() as cur: sql = "DELETE FROM t_chat_history WHERE id = %s" await cur.execute(sql, (chat_id,)) logger.info(f"成功删除聊天记录 ID: {chat_id}") except Exception as e: logger.error(f"删除聊天记录失败: {str(e)}") raise async def main(): """主函数""" pool = None try: # 初始化连接池 pool = await init_mysql_pool() # 清空表 await truncate_chat_log(pool) # 测试插入 person_id = str(uuid.uuid4()) chat_id = await insert_chat_log( pool=pool, chat_text="你好,小智", chat_wav="test.wav", ai_text="你好,有什么我可以帮你的吗?", person_id=person_id, person_name="测试用户" ) logger.info(f"插入的聊天记录ID: {chat_id}") # 测试更新 await update_chat_log( pool=pool, chat_id=chat_id, ai_text="你好,很高兴为你服务!", person_name="更新后的用户" ) # 测试删除 await delete_chat_log(pool, chat_id) except Exception as e: logger.error(f"程序执行出错: {str(e)}") finally: if pool: pool.close() await pool.wait_closed() logger.info("MySQL连接池已关闭") if __name__ == '__main__': asyncio.run(main())