修正資料庫未關閉問題
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user