MySQL.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const mysql = require('mysql2/promise');
  2. const path = require('path');
  3. const config = require('../../config.json');
  4. const Logger = require('../../lib/Logger');
  5. class MySQL {
  6. constructor() {
  7. this.config = config.database;
  8. this.connection = null;
  9. this.logger = new Logger(path.join(__dirname, '../../logs/MySQL.log'), 'INFO');
  10. }
  11. async connect() {
  12. if (!this.connection) {
  13. try {
  14. this.logger.info('正在连接数据库');
  15. this.connection = await mysql.createConnection(this.config);
  16. this.logger.info('已连接到数据库');
  17. return this.connection;
  18. } catch (error) {
  19. this.logger.error('连接数据库失败:', error.message);
  20. throw error;
  21. }
  22. } else {
  23. try {
  24. // 检查当前连接的有效性
  25. await this.connection.ping();
  26. return this.connection;
  27. } catch (error) {
  28. this.logger.warn('数据库连接失效,尝试重新连接...');
  29. this.connection = null; // 清除当前连接
  30. return await this.connect(); // 递归调用 connect() 重新连接
  31. }
  32. }
  33. }
  34. async query(sql, params = []) {
  35. try {
  36. // 确保在执行查询之前连接已建立并有效
  37. await this.connect();
  38. const [rows] = await this.connection.execute(sql, params);
  39. return rows;
  40. } catch (error) {
  41. this.logger.error(`执行SQL语句时出错:${error.stack}`);
  42. }
  43. }
  44. async close() {
  45. if (this.connection) {
  46. try {
  47. await this.connection.end();
  48. this.logger.info('已关闭与数据库的连接');
  49. this.connection = null;
  50. } catch (error) {
  51. this.logger.error('关闭与数据库的连接时出错:', error);
  52. throw error;
  53. }
  54. }
  55. }
  56. }
  57. module.exports = MySQL;