const mysql = require('mysql2/promise'); const path = require('path') const config = require('../../config.json'); const Logger = require('../../lib/Logger'); class MySQL { constructor() { this.config = config.database; this.connection = null; this.logger = new Logger(path.join(__dirname, '../logs/MySQL.log'), 'INFO') } async connect() { if (this.connection) { return this.connection; } try { this.logger.info('正在连接数据库') this.connection = await mysql.createConnection(this.config); this.logger.info('已连接到数据库') return this.connection; } catch (error) { this.logger.error('连接数据库失败:', error.message) throw error; } } async query(sql, params = []) { try { const [rows, fields] = await this.connection.execute(sql, params); return { rows, fields }; } catch (error) { this.logger.error('执行SQL语句时出错:', error); throw error; } } async close() { if (this.connection) { try { await this.connection.end(); this.logger.info('已关闭与数据库的连接') this.connection = null; } catch (error) { this.logger.error('关闭与数据库的连接时出错:', error); throw error; } } } } module.exports = MySQL;