import mysql from 'mysql2/promise'; import dotenv from 'dotenv'; dotenv.config(); const dbConfig = { host: process.env.DB_HOST || 'mysql.theaken.com', port: parseInt(process.env.DB_PORT) || 33306, user: process.env.DB_USER || 'A102', password: process.env.DB_PASSWORD || 'Bb123456', database: process.env.DB_NAME || 'db_A102' }; async function testConnection() { let connection; try { console.log('\n╔═══════════════════════════════════════╗'); console.log('║ Database Connection Test ║'); console.log('╚═══════════════════════════════════════╝\n'); console.log('📡 Attempting to connect to database...'); console.log(` Host: ${dbConfig.host}`); console.log(` Port: ${dbConfig.port}`); console.log(` Database: ${dbConfig.database}`); console.log(` User: ${dbConfig.user}\n`); connection = await mysql.createConnection(dbConfig); console.log('✅ Connection successful!\n'); // 測試基本查詢 console.log('🔍 Testing basic queries...\n'); // 1. 檢查資料庫版本 const [versionResult] = await connection.execute('SELECT VERSION() as version'); console.log(` MySQL Version: ${versionResult[0].version}`); // 2. 列出所有資料表 const [tables] = await connection.execute('SHOW TABLES'); console.log(` Tables found: ${tables.length}`); if (tables.length > 0) { console.log('\n📊 Available tables:'); tables.forEach((table, index) => { const tableName = Object.values(table)[0]; console.log(` ${index + 1}. ${tableName}`); }); // 3. 檢查每個資料表的記錄數 console.log('\n📈 Table statistics:'); for (const table of tables) { const tableName = Object.values(table)[0]; const [countResult] = await connection.execute(`SELECT COUNT(*) as count FROM \`${tableName}\``); console.log(` ${tableName}: ${countResult[0].count} rows`); } } else { console.log('\n⚠️ No tables found. Run "npm run db:init" to initialize the database.'); } console.log('\n✅ All tests passed!\n'); } catch (error) { console.error('\n❌ Connection failed!'); console.error(` Error: ${error.message}`); if (error.code) { console.error(` Error Code: ${error.code}`); } if (error.errno) { console.error(` Error Number: ${error.errno}`); } console.log('\n💡 Troubleshooting tips:'); console.log(' 1. Check if MySQL server is running'); console.log(' 2. Verify host and port in .env file'); console.log(' 3. Confirm database credentials'); console.log(' 4. Check firewall settings'); console.log(' 5. Ensure database exists\n'); process.exit(1); } finally { if (connection) { await connection.end(); console.log('🔌 Connection closed\n'); } } } testConnection();