65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import mysql from 'mysql2/promise';
|
|
import { dbConfig } from './config';
|
|
|
|
// 建立連接池
|
|
const pool = mysql.createPool({
|
|
...dbConfig,
|
|
waitForConnections: true,
|
|
connectionLimit: 10,
|
|
queueLimit: 0,
|
|
});
|
|
|
|
// 資料庫連接函數
|
|
export async function getConnection() {
|
|
try {
|
|
const connection = await pool.getConnection();
|
|
return connection;
|
|
} catch (error) {
|
|
console.error('資料庫連接失敗:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// 執行查詢函數
|
|
export async function query(sql: string, params?: any[]) {
|
|
try {
|
|
const [rows] = await pool.execute(sql, params);
|
|
return rows;
|
|
} catch (error) {
|
|
console.error('查詢執行失敗:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// 執行事務函數
|
|
export async function transaction(callback: (connection: mysql.PoolConnection) => Promise<any>) {
|
|
const connection = await pool.getConnection();
|
|
try {
|
|
await connection.beginTransaction();
|
|
const result = await callback(connection);
|
|
await connection.commit();
|
|
return result;
|
|
} catch (error) {
|
|
await connection.rollback();
|
|
throw error;
|
|
} finally {
|
|
connection.release();
|
|
}
|
|
}
|
|
|
|
// 測試資料庫連接
|
|
export async function testConnection() {
|
|
try {
|
|
const connection = await getConnection();
|
|
await connection.ping();
|
|
connection.release();
|
|
console.log('✅ 資料庫連接成功');
|
|
return true;
|
|
} catch (error) {
|
|
console.error('❌ 資料庫連接失敗:', error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export default pool;
|