修正資料庫未關閉問題

This commit is contained in:
2025-09-21 21:23:47 +08:00
parent 36e29c5a3f
commit 38ae30d611
11 changed files with 684 additions and 111 deletions

View File

@@ -462,8 +462,24 @@ export class DatabaseFailover {
try {
connection = await this.getConnection();
const [rows] = await connection.execute(sql, params);
// 完全關閉連線
await connection.destroy();
connection = null;
console.log('✅ 備援查詢連線已完全關閉');
return rows as T[];
} catch (error: any) {
// 確保連線被關閉
if (connection) {
try {
await connection.destroy();
} catch (destroyError) {
console.error('關閉連線時發生錯誤:', destroyError);
}
connection = null;
}
console.error(`資料庫查詢錯誤 (嘗試 ${retries + 1}/${maxRetries}):`, error.message);
console.error('查詢錯誤詳情:', {
code: error.code,
@@ -540,36 +556,60 @@ export class DatabaseFailover {
}
}
// 執行插入
// 執行插入 - 每次查詢完就完全關閉連線
public async insert(sql: string, params?: any[]): Promise<mysql.ResultSetHeader> {
const connection = await this.getConnection();
let connection;
try {
connection = await this.getConnection();
const [result] = await connection.execute(sql, params);
return result as mysql.ResultSetHeader;
} finally {
connection.release();
if (connection) {
try {
await connection.destroy();
console.log('✅ 備援插入連線已完全關閉');
} catch (destroyError) {
console.error('關閉連線時發生錯誤:', destroyError);
}
}
}
}
// 執行更新
// 執行更新 - 每次查詢完就完全關閉連線
public async update(sql: string, params?: any[]): Promise<mysql.ResultSetHeader> {
const connection = await this.getConnection();
let connection;
try {
connection = await this.getConnection();
const [result] = await connection.execute(sql, params);
return result as mysql.ResultSetHeader;
} finally {
connection.release();
if (connection) {
try {
await connection.destroy();
console.log('✅ 備援更新連線已完全關閉');
} catch (destroyError) {
console.error('關閉連線時發生錯誤:', destroyError);
}
}
}
}
// 執行刪除
// 執行刪除 - 每次查詢完就完全關閉連線
public async delete(sql: string, params?: any[]): Promise<mysql.ResultSetHeader> {
const connection = await this.getConnection();
let connection;
try {
connection = await this.getConnection();
const [result] = await connection.execute(sql, params);
return result as mysql.ResultSetHeader;
} finally {
connection.release();
if (connection) {
try {
await connection.destroy();
console.log('✅ 備援刪除連線已完全關閉');
} catch (destroyError) {
console.error('關閉連線時發生錯誤:', destroyError);
}
}
}
}