2025-04-24 11:02:41 +08:00
|
|
|
import mysql from 'mysql';
|
2025-04-24 11:59:10 +08:00
|
|
|
import { cdkDbConfig } from '../config/db.config';
|
2025-04-24 11:02:41 +08:00
|
|
|
|
|
|
|
|
// 创建连接池
|
2025-04-24 11:59:10 +08:00
|
|
|
const pool = mysql.createPool(cdkDbConfig);
|
2025-04-24 11:02:41 +08:00
|
|
|
|
|
|
|
|
// 获取数据库连接
|
|
|
|
|
export const getConnection = (): Promise<mysql.PoolConnection> => {
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
pool.getConnection((err, connection) => {
|
|
|
|
|
if (err) {
|
|
|
|
|
reject(err);
|
|
|
|
|
} else {
|
|
|
|
|
resolve(connection);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// 执行查询
|
2025-04-24 11:59:10 +08:00
|
|
|
export const query = async (sql: string, values?: any[], connection?: mysql.PoolConnection): Promise<any> => {
|
|
|
|
|
if (!connection) {
|
|
|
|
|
connection = await getConnection()
|
|
|
|
|
}
|
2025-04-24 11:02:41 +08:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
connection.query(sql, values, (err, results) => {
|
|
|
|
|
connection.release(); // 释放连接
|
|
|
|
|
if (err) {
|
|
|
|
|
reject(err);
|
|
|
|
|
} else {
|
|
|
|
|
resolve(results);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
};
|