| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- import mysql from 'mysql2/promise';
- import { readFileSync } from 'fs';
- import { join } from 'path';
- // 尝试从config.json文件读取配置
- let jsonConfig: any = {};
- try {
- // 从项目根目录读取config.json文件
- const configPath = join(process.cwd(), 'config.json');
- const configContent = readFileSync(configPath, 'utf-8');
- jsonConfig = JSON.parse(configContent);
- } catch (error) {
- console.log('⚠️ 无法读取config.json,将使用环境变量或默认值');
- }
- // 数据库配置
- const config = {
- host: process.env.DB_HOST || jsonConfig.db?.host || 'localhost',
- port: Number(process.env.DB_PORT) || jsonConfig.db?.port || 3306,
- user: process.env.DB_USER || jsonConfig.db?.user || 'root',
- password: process.env.DB_PASSWORD || jsonConfig.db?.password || '',
- database: process.env.DB_NAME || jsonConfig.db?.database || 'protection_center',
- waitForConnections: true,
- connectionLimit: 10,
- queueLimit: 0
- };
- // 创建连接池
- const pool = mysql.createPool(config);
- // 测试数据库连接
- async function testConnection() {
- try {
- const connection = await pool.getConnection();
- console.log('✅ 数据库连接成功');
- connection.release();
- } catch (error) {
- console.error('❌ 数据库连接失败:', error);
- throw error;
- }
- }
- export {
- pool,
- testConnection,
- config
- };
|