""" 数据库连接服务模块 提供统一的数据库连接接口 """ from sqlalchemy import create_engine from urllib.parse import quote_plus import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def create_db_connection(host, port, database, username, password): """ 创建数据库连接 Args: host: 数据库主机地址 port: 端口 database: 数据库名 username: 用户名 password: 密码 Returns: SQLAlchemy engine对象 """ try: # 对密码进行URL编码,处理特殊字符 encoded_password = quote_plus(password) # 构建连接字符串 connection_string = f'mysql+pymysql://{username}:{encoded_password}@{host}:{port}/{database}' # 创建引擎 engine = create_engine( connection_string, pool_pre_ping=True, # 连接池预检 pool_recycle=3600, # 连接回收时间 echo=False ) logger.info(f"Database connection created successfully: {host}:{port}/{database}") return engine except Exception as e: logger.error(f"Failed to create database connection: {e}") raise