35 lines
976 B
TypeScript
35 lines
976 B
TypeScript
import mysql from 'mysql';
|
|
import { cdkDbConfig } from '../config/db.config';
|
|
|
|
// 创建连接池
|
|
const pool = mysql.createPool(cdkDbConfig);
|
|
|
|
// 获取数据库连接
|
|
export const getConnection = (): Promise<mysql.PoolConnection> => {
|
|
return new Promise((resolve, reject) => {
|
|
pool.getConnection((err, connection) => {
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve(connection);
|
|
}
|
|
});
|
|
});
|
|
};
|
|
|
|
// 执行查询
|
|
export const query = async (sql: string, values?: any[], connection?: mysql.PoolConnection): Promise<any> => {
|
|
if (!connection) {
|
|
connection = await getConnection()
|
|
}
|
|
return new Promise((resolve, reject) => {
|
|
connection.query(sql, values, (err, results) => {
|
|
connection.release(); // 释放连接
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve(results);
|
|
}
|
|
});
|
|
});
|
|
}; |