1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- 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) {
- 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;
- }
- } else {
- try {
- // 检查当前连接的有效性
- await this.connection.ping();
- return this.connection;
- } catch (error) {
- this.logger.warn('数据库连接失效,尝试重新连接...');
- this.connection = null; // 清除当前连接
- return await this.connect(); // 递归调用 connect() 重新连接
- }
- }
- }
- async query(sql, params = []) {
- try {
- // 确保在执行查询之前连接已建立并有效
- await this.connect();
- const [rows] = await this.connection.execute(sql, params);
- return rows;
- } catch (error) {
- this.logger.error(`执行SQL语句时出错:${error.stack}`);
- }
- }
- 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;
|