MySQL.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. return this.connection;
  14. }
  15. try {
  16. this.logger.info('正在连接数据库')
  17. this.connection = await mysql.createConnection(this.config);
  18. this.logger.info('已连接到数据库')
  19. return this.connection;
  20. } catch (error) {
  21. this.logger.error('连接数据库失败:', error.message)
  22. throw error;
  23. }
  24. }
  25. async query(sql, params = []) {
  26. try {
  27. const [rows] = await this.connection.execute(sql, params);
  28. return rows;
  29. } catch (error) {
  30. this.logger.error(`执行SQL语句时出错:${error.stack}`);
  31. throw error;
  32. }
  33. }
  34. async close() {
  35. if (this.connection) {
  36. try {
  37. await this.connection.end();
  38. this.logger.info('已关闭与数据库的连接')
  39. this.connection = null;
  40. } catch (error) {
  41. this.logger.error('关闭与数据库的连接时出错:', error);
  42. throw error;
  43. }
  44. }
  45. }
  46. }
  47. module.exports = MySQL;