89 lines
2.7 KiB
JavaScript
89 lines
2.7 KiB
JavaScript
import mysql from 'mysql2/promise';
|
|
import 'dotenv/config';
|
|
|
|
// 引入database.js配置
|
|
import dbConfig from '../src/config/database';
|
|
|
|
// 尝试多种连接配置
|
|
async function testMySQLConnections() {
|
|
console.log('🔍 测试MySQL连接配置...\n');
|
|
|
|
// 使用database.js中的配置
|
|
const config1 = {
|
|
host: dbConfig.pool.config.host,
|
|
port: dbConfig.pool.config.port,
|
|
user: dbConfig.pool.config.user,
|
|
password: dbConfig.pool.config.password,
|
|
database: dbConfig.pool.config.database,
|
|
connectTimeout: 5000
|
|
};
|
|
|
|
// 配置2: 不指定数据库名称
|
|
const config2 = {
|
|
...config1,
|
|
database: undefined
|
|
};
|
|
|
|
const configurations = [
|
|
{ name: 'database.js配置', config: config1 },
|
|
{ name: 'database.js配置(无数据库)', config: config2 }
|
|
];
|
|
|
|
for (const { name, config } of configurations) {
|
|
console.log(`\n🎯 尝试连接: ${name}`);
|
|
console.log(`📌 配置:`, {
|
|
host: config.host,
|
|
port: config.port,
|
|
user: config.user,
|
|
database: config.database || '不指定'
|
|
});
|
|
|
|
try {
|
|
const connection = await mysql.createConnection(config);
|
|
console.log('✅ 连接成功!');
|
|
|
|
// 测试简单查询
|
|
const [rows] = await connection.execute('SELECT 1 as test');
|
|
console.log('✅ 查询测试通过:', rows);
|
|
|
|
// 如果指定了数据库,检查数据库是否存在
|
|
if (config.database) {
|
|
const [dbCheck] = await connection.execute(`SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?`, [config.database]);
|
|
if (dbCheck.length > 0) {
|
|
console.log('✅ 数据库存在');
|
|
} else {
|
|
console.warn('⚠️ 指定的数据库不存在');
|
|
}
|
|
}
|
|
|
|
await connection.end();
|
|
return { success: true, config };
|
|
|
|
} catch (error) {
|
|
console.error('❌ 连接失败:', error.message);
|
|
console.error('🔍 错误代码:', error.code);
|
|
|
|
if (error.code === 'ECONNREFUSED') {
|
|
console.error('💡 可能原因: MySQL服务器未启动或网络不可达');
|
|
} else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
|
|
console.error('💡 可能原因: 用户名或密码错误');
|
|
} else if (error.code === 'ER_BAD_DB_ERROR') {
|
|
console.error('💡 可能原因: 数据库不存在');
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log('\n❌ 所有连接配置都失败了');
|
|
console.log('💡 建议:');
|
|
console.log('1. 检查MySQL服务器是否已启动');
|
|
console.log('2. 确认用户名和密码正确');
|
|
console.log('3. 确认数据库已创建');
|
|
console.log('4. 检查网络连接');
|
|
|
|
return { success: false };
|
|
}
|
|
|
|
// 执行测试
|
|
testMySQLConnections().then(result => {
|
|
process.exit(result.success ? 0 : 1);
|
|
}); |