db.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import mysql from 'mysql2/promise';
  2. import { readFileSync } from 'fs';
  3. import { join } from 'path';
  4. // 尝试从config.json文件读取配置
  5. let jsonConfig: any = {};
  6. try {
  7. // 从项目根目录读取config.json文件
  8. const configPath = join(process.cwd(), 'config.json');
  9. const configContent = readFileSync(configPath, 'utf-8');
  10. jsonConfig = JSON.parse(configContent);
  11. } catch (error) {
  12. console.log('⚠️ 无法读取config.json,将使用环境变量或默认值');
  13. }
  14. // 数据库配置
  15. const config = {
  16. host: process.env.DB_HOST || jsonConfig.db?.host || 'localhost',
  17. port: Number(process.env.DB_PORT) || jsonConfig.db?.port || 3306,
  18. user: process.env.DB_USER || jsonConfig.db?.user || 'root',
  19. password: process.env.DB_PASSWORD || jsonConfig.db?.password || '',
  20. database: process.env.DB_NAME || jsonConfig.db?.database || 'protection_center',
  21. waitForConnections: true,
  22. connectionLimit: 10,
  23. queueLimit: 0
  24. };
  25. // 创建连接池
  26. const pool = mysql.createPool(config);
  27. // 测试数据库连接
  28. async function testConnection() {
  29. try {
  30. const connection = await pool.getConnection();
  31. console.log('✅ 数据库连接成功');
  32. connection.release();
  33. } catch (error) {
  34. console.error('❌ 数据库连接失败:', error);
  35. throw error;
  36. }
  37. }
  38. export {
  39. pool,
  40. testConnection,
  41. config
  42. };