/** * @file MySQLConnection.ts * @version 1.0.1 * @description MySQL数据库连接池 * * 该文件提供了MySQL数据库连接池的实现,包括以下功能: * - 创建数据库连接池 * - 自动测试数据库连接 * - 数据库基础错误处理 * * ## 配置项说明 * 在 `config.ts` 文件中,可以配置以下选项: * - `enable`: 是否启用 MySQL 数据库 * - `host`: 数据库主机地址 * - `port`: 数据库端口号 * - `database`: 数据库名称 * - `user`: 数据库用户名 * - `password`: 数据库密码 * */ import mysql from "mysql2/promise"; import Logger from "@lib/Logger/Logger"; import config from "../../config"; class MySQLConnectPool { private pool: any; private logger = new Logger('MySQL'); constructor() { if (!config.mysql.enable) { this.logger.warn('Database is disabled, initialization terminated'); return; } this.pool = this.createConnectPool(); this.logger.info("Database connection pool created") setTimeout(async () => { let res = await this.testConnection(); if (res) this.logger.info("Database test successful") else this.logger.error("Database test failed") }, 10); } private createConnectPool() { return mysql.createPool({ host: config.mysql.host, database: config.mysql.database, port: config.mysql.port, user: config.mysql.user, password: config.mysql.password, waitForConnections: true, connectionLimit: 10, queueLimit: 0 }) } private async testConnection() { try { let res = await this.execute("SELECT 1 + 1 As result"); if (res[0].result == 2) return 1; else return 0; } catch (error) { this.logger.error(`An error occurred during the database test: ` + error); return 0; } } /** * 执行SQL查询 * @param sql SQL语句 * @param values 可选的查询参数列表 * @param database 可选的数据库 * @returns Promise 查询结果 */ public async execute(sql: string, values?: any[], database?: string): Promise { let connection: any; try { connection = await this.pool.getConnection(); // 如果指定了数据库,则更改当前连接的数据库 if (database) { await connection.changeUser({ database }); } let [rows, fields] = await connection.execute(sql, values); return rows; } catch (error) { this.logger.error("An error occurred in the database: " + error, '\n##', sql, '\n##', JSON.stringify(values)); return undefined; } finally { if (database) await connection.changeUser({ database: config.mysql.database });// 恢复默认数据库 if (connection) connection.release(); } } } const MySQLConnection = new MySQLConnectPool(); export default MySQLConnection;